沃梦达 / 编程问答 / php问题 / 正文

Laravel 5.4 - 使用正则表达式验证

Laravel 5.4 - Validation with Regex(Laravel 5.4 - 使用正则表达式验证)

本文介绍了Laravel 5.4 - 使用正则表达式验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的项目名称规则:

$this->validate(request(), [
    'projectName' => 'required|regex:/(^([a-zA-z]+)(d+)?$)/u',
];

我正在尝试添加规则,使其必须以 来自 azAz 的字母开头,并且可以以数字结尾,但大多数不是.

I am trying to add the rule such that it must start with a letter from a-z or A-z and can end with numbers but most not.

项目名称的有效值:

myproject123
myproject
MyProject

项目名称的无效值:

123myproject
!myproject
myproject 123
my project
my project123

我在线尝试了我的正则表达式:

I tried my regex online:

https://regex101.com/r/FylFY1/2

它应该可以工作,但即使使用 project 123 我也可以通过验证.

It should work, but I can pass the validation even with project 123.

更新:它确实有效,我只是在错误的控制器中测试了它,对不起...但也许它仍然会帮助其他人

UPDATE: It actually works, I just tested it in the wrong controller, im sorry... but maybe it will help others nevertheless

推荐答案

你的规则做得很好但是你需要知道,用管道分隔的正则表达式指定验证规则可以导致强> 到不受欢迎的行为.

Your rule is well done BUT you need to know, specify validation rules with regex separated by pipeline can lead to undesired behavior.

定义验证规则的正确方法应该是:

The proper way to define a validation rule should be:

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

您可以阅读官方文档:

正则表达式:模式

验证字段必须与给定的正则表达式匹配.

The field under validation must match the given regular expression.

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

Note: When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

这篇关于Laravel 5.4 - 使用正则表达式验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Laravel 5.4 - 使用正则表达式验证

基础教程推荐