首页 > 解决方案 > laravel 自定义验证问题它无法正常工作,给出了一些错误,一些没有给出

问题描述

这是我的验证代码,但没有给出正确的验证错误。它只显示这些错误

不允许使用特殊字符,如 \t、:、\n 需要 GivenName 需要 MiddleName 而需要最大字段

$this->validate($request,[
            'DisplayName'=>'required|max:500',
            'DisplayName'=>'regex:/(^[A-Za-z0-9]+$)+/',
            'GivenName'  => 'required|max:100',
            'MiddleName' =>'required|max:100',
            'Title'      => 'max:16',
            'Suffix'     =>'max:16',
            'FamilyName' =>'max:100'
        ],
        [
            'DisplayName.required'     => 'DisplayName is required!',
            'DisplayName.regex'        => 'Special character is not allowed like \t, :, \n ',
            'GivenName.max'            =>'GivenName is max 100 words',
            'GivenName.required'       =>'GivenName is required',
            'MiddleName.max'           =>'MiddleName is max 100 words',
            'MiddleName.required'      =>'MiddleName is required',
            'Title.max'                =>'Title is max 16 words',  
            'Suffix.max'               =>'Suffix is max 16 words',
            'FamilyName.max'           =>'FamilyName is 100 words'
        ],

标签: laravellaravel-validation

解决方案


使用该regex模式时,可能需要在数组中指定规则而不是使用管道分隔符,尤其是当正则表达式包含管道字符时,例如:

$this->validate(request(), [
    'userName' => 
        array(
            'required',
            'regex:/(^([a-zA-Z]+)(\d+)?$)/u'
        )
]);

所以你的代码应该是:

$this->validate($request,[
        'DisplayName' => 
            array(
              'required',
              'max:500',
              'regex:/(^[A-Za-z0-9]+$)+/'
            ),
         'GivenName'  => 'required|max:100',
         'MiddleName' =>'required|max:100',
         'Title'      => 'max:16',
         'Suffix'     =>'max:16',
         'FamilyName' =>'max:100'
     ],
     [
         'DisplayName.required'     => 'DisplayName is required!',
         'DisplayName.regex'        => 'Special character is not allowed like \t, :, \n ',
         'GivenName.max'            =>'GivenName is max 100 words',
         'GivenName.required'       =>'GivenName is required',
         'MiddleName.max'           =>'MiddleName is max 100 words',
         'MiddleName.required'      =>'MiddleName is required',
         'Title.max'                =>'Title is max 16 words',  
         'Suffix.max'               =>'Suffix is max 16 words',
         'FamilyName.max'           =>'FamilyName is 100 words'
     ],
);

推荐阅读