验证定制规则Laravel
我已经制定了一个自定义规则来验证移动设备。有特定的模式和要求。
图案 [0-9] {3} - [0-9] {4} - [0-9] {4}
前三位数字应该是以下数字之一:
010,020,030 ,040、050、060、070、080、090
以下是我的自定义规则的代码。
app/rules/mobilenumber.php
public function passes($attribute, $value)
{
$pattern = "/^\[0-9]{4}-[0-9]{4}-[0-9]{3}$/";
return preg_match($pattern, $value);
}
我的自定义验证器:
app/http/request/userrequest.php ,
use App\Rules\MobileNumber;
......
//manipulate data before validation
public function validationData()
{
$this->merge([
'tel_number' => $this->tel_number_1.'-'. $this->tel_number_2.'-'.$this->tel_number_3,
]);
}
public function rules()
{
return [
//other rules here....
'mob_number' => 'required', new MobileNumber()
];
}
但使用上述代码验证不起作用。tel_number
tel_number < /代码>未达到
通过
检查验证的方法。 即,如果用户给出字母字符或符号,则将其转发用于数据库保存方法。
因此,我无法检查我的正则是正确的。
如果有人能突出我在这里犯的错误,那将非常有帮助。另外,请确认我的正则是正确通过验证的正确性。
I have made a custom rule to validate mobile no. with specific pattern and requirement.
Pattern[0-9]{3}-[0-9]{4}-[0-9]{4}
The first three digits should be one of the following numbers:
010, 020, 030, 040, 050, 060, 070, 080, 090
Below is my code for custom rule.
App/Rules/MobileNumber.php
public function passes($attribute, $value)
{
$pattern = "/^\[0-9]{4}-[0-9]{4}-[0-9]{3}$/";
return preg_match($pattern, $value);
}
My custom validator:
app/HTTP/Request/UserRequest.php
use App\Rules\MobileNumber;
......
//manipulate data before validation
public function validationData()
{
$this->merge([
'tel_number' => $this->tel_number_1.'-'. $this->tel_number_2.'-'.$this->tel_number_3,
]);
}
public function rules()
{
return [
//other rules here....
'mob_number' => 'required', new MobileNumber()
];
}
But with the above code the validation is not working.tel_number
is not reaching to passes
method to check for validation.
I.E If user gives alphabetic char or symbols they are being forwarded for database save method.
So I cannot check if my regex is correct or not.
It would be very helpful if someone could highlight the mistake I've made here. Also confirm if my regex is correct to pass the validation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我只能回答正则验证的最后一点。
您将实现中的顺序切换到4-4-3,而不是3-4-4位数字。
序列010,020,030,040,050,060,070,080,090可以使用
0 [1-9] 0
匹配,您不应逃脱\ [否则您将以字面意义匹配。
更新的代码可能看起来像:
I can only answer the last point for the regex validation.
You switched the order in the implementation to 4-4-3 instead of 3-4-4 digits.
The sequences 010, 020, 030, 040, 050, 060, 070, 080, 090 can be matched using
0[1-9]0
and you should not escape the\[
or else you will match it literally.The updated code might look like: