简体   繁体   English

Laravel时间24h格式正则表达式错误(无结束分隔符)

[英]Laravel time 24h format regex error (No ending delimiter)

So I have this: 所以我有这个:

'title' => 'required|max:100|regex:/^(?=.*[a-zA-Z]).+$/',
'start_time' => 'date_format:H:i|regex:/^((([01]?[0-9]|2[0-3]):[0-5][0-9])?)$/',

title is working perfect (the user has to enter at least 1 letter) But I'm having problems with start_time which is returning 标题工作正常(用户必须输入至少1个字母)但是我遇到了start_time的问题,而这正在返回

preg_match(): No ending delimiter '/' found", exception: "ErrorException",…} preg_match():没有结束分隔符'/'found“,异常:”ErrorException“,...}

What I want is to validate 24h format with the possibility that the user ads AM or PM, for example: 05:10 PM, so I want to validate the first 5 characters and free the rest, I think it's correct. 我想要的是验证24小时格式与用户广告AM或PM的可能性,例如:下午05:10,所以我想验证前5个字符并释放其余的,我认为这是正确的。

So, what am I missing to make it run? 那么,我错过了什么让它运行?

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: 定义验证规则的正确方法应该是:

'title' => 'required|max:100|regex:/^(?=.*[a-zA-Z]).+$/',
'start_time' => ['date_format:H:i','regex:/^((([01]?[0-9]|2[0-3]):[0-5][0-9])?)$/'],

You can read on the official docs: 您可以阅读官方文档:

regex:pattern 正则表达式:模式

The field under validation must match the given regular expression. 验证字段必须与给定的正则表达式匹配。

Note: When using the regex pattern, it may be necessary to specify rules in an array instead of using pipe delimiters , especially if the regular expression contains a pipe character. 注意:使用正则表达式模式时,可能需要在数组中指定规则而不是使用管道分隔符 ,尤其是在正则表达式包含管道符时。

https://laravel.com/docs/5.6/validation#rule-regex https://laravel.com/docs/5.6/validation#rule-regex

Try this: 尝试这个:

'start_time' => ['date_format:H:i', 'regex:/^((([01]?[0-9]|2[0-3]):[0-5][0-9])?)$/'],

The problem is the | 问题是| character in the regular expression. 正则表达式中的字符。 Laravel uses it as a separator between rules. Laravel将它用作规则之间的分隔符。

The character pipe | 字符管| in regex conflicts with | 在正则表达式与|冲突 in seprating rules. 在制定规则时。 You have to initialize an array: 你必须初始化一个数组:

'start_time' => ['date_format:H:i', 'regex:/^((([01]?[0-9]|2[0-3]):[0-5][0-9])?)$/']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM