PHP code example of slpcode / form-request-validation

1. Go to this page and download the library: Download slpcode/form-request-validation library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

slpcode / form-request-validation example snippets




use Slpcode\FormRequestValidation\FormRequest;

class TestRequest extends FormRequest
{
    /**
     * 设置验证规则
     *
     * @return array
     */
    protected function rules()
    {
        return [
            'name' => '
     * @return array
     */
    protected function attributes()
    {
        return [];
    }
}

 

// 进行验证,如果验证不通过则会抛出 Slpcode\FormRequestValidation\Exceptions\ValidationException 异常
// 通过后返回request实例

$request = (new TestRequest)->check();



class BaseRequest extends \Slpcode\FormRequestValidation\FormRequest
{
    public function extend(){
        $this->getValidator()->extend('mobile', function ($attribute, $value, $parameters, $validator) {
//            return ...;
        }, ':attribute 格式不正确');
    }
}



class BaseRequest extends \Slpcode\FormRequestValidation\FormRequest
{
    protected $translation_path = __DIR__ . '/lang';
    protected $translation_locale = 'en';
}

// 或
(new TestRequest)->setLang('en', '语言包路径');



// 直接创建验证器对象的用法
$validator = \Slpcode\FormRequestValidation\Validator::getInstance();

//验证
$rules = [
    'name' => '�不能为空',
    //...
]; 
// 可选
// 自定义属性名称
$attributes = [
    'name' => '用户名',
    'age' => '年龄',
];
$validatorObj = $validator->make($data, $rules, $messages, $attributes);
//判断验证是否通过
if ($validatorObj->fails()) {
   //未通过
   //输出错误消息
   dd($validatorObj->messages()->all());
} else {
    
}


$validator = \Slpcode\FormRequestValidation\Validator::getInstance();
$validator->extend(
    'mobile', 
    function ($attribute, $value, $parameters, $validator) {
//      return ...;
    }, ':attribute 格式不正确');



// 内部有两种语言包 en 和 zh-CN
$validator = \Slpcode\FormRequestValidation\Validator::getInstance('en', '路径');