php Laravel中字符串长度的规则验证

a11xaf1n  于 2022-10-30  发布在  PHP
关注(0)|答案(3)|浏览(516)

我需要验证一个长度正好为6或8的字符串。我该如何制定验证规则?
数字必须是6或8,不能介于6和8之间。

vsdwdz23

vsdwdz231#

您需要创建自定义规则。
在下面的示例中,我使用Closure创建了一个自定义规则,但是您可以创建一个规则对象来重用它。
我使用mb_strlen而不是strlen来覆盖多字节。(UTF8字符)

use Illuminate\Support\Facades\Validator;
use \Illuminate\Http\Request;

Route::get('/test', function (Request $request) {
    $validator = Validator::make($request->all(), [
        'title' => [
            'required',
            function ($attribute, $value, $fail) {
                if (!(mb_strlen($value) == 8 || mb_strlen($value) == 6))
                {
                    $fail('The ' . $attribute . ' is invalid.');
                }
            },
        ],
    ]);

    dd($validator->errors());
});
kmbjn2e3

kmbjn2e32#

实际上,您不需要创建自己的验证器,因为Laravel的验证带有一个regex验证规则,因此您只需执行以下操作:

[
    ...
    'parameter' => 'regex:/^(.{6}|.{8})$/g',
    ...
]

正则表达式是从here偷来的,但您可以在here上测试它

正则表达式解释:

^    # Start of string
(    # Start capture group
.    # Matches any character except line breaks
{6}  # Quantifier that only matches 6 preceding tokens (.)
|    # OR operator
.    # Matches any character except line breaks
{8}  # Quantifier that only matches 8 preceding tokens (.)
)    # End capture group
$    # End of string

旧答案(不必要的复杂)

[
    ...
    'parameter' => 'regex:/^(?=.*$)(?:.{6}|.{8})$/g',
    ...
]

正则表达式解释:

^    # Start of string
(?=  # Start of positive lookahead
.*   # Matches any character except line breaks 0 or more times
$    # End of string
)    # End of positive lookahead
(?:  # Start of non-capturing group
.{6} # Matches any character except line breaks exactly 6 times
|    # OR operator
.{8} # Matches any character except line breaks exactly 8 times
)    # End non-capturing group
$    # End of string
piztneat

piztneat3#

请先尝试保存字符串长度,然后检查if条件。

$str = “hellowld”;
$len = strlen($str);
If($len == 6 || $len == 8)
    //do something 
Else
    //throw error

或者使用regex长度验证规则,如下所示:

/^[68]+$/

表示字符串长度。

相关问题