Laravel 验证正则表达式,视图中断

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18963085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:28:04  来源:igfitidea点击:

Laravel validation regex, breaks in view

phphtmlregexvalidationlaravel

提问by Alex

So, I have the following rules in my model:

所以,我的模型中有以下规则:

public static $rules = array(
    'name'            => 'required|alpha_dash|unique:subsidiaries',
    'internal_number' => 'required|alpha_dash|unique:subsidiaries',
    'expedition_rate' => array('required', 'regex:/^[0-9]{1,3}(\.?)[0-9]{1,2}$/'),
    'hundred_kg_rate' => array('regex:/^[0-9]{1,5}(\.?)[0-9]{1,2}$/'),
    'handling'        => array('regex:/^[0-9]{1,3}(\.?)[0-9]{1,2}$/'),
    'insurance'       => 'required|numeric',
);

But, for some reason, when the regex is applied in the patternattribute tag in html... it breaks!

但是,由于某种原因,当pattern在 html的属性标记中应用正则表达式时……它会中断!

Result:

结果:

<input required="true" pattern="^[0-9]{" class="form-control" ....>
                               _________
                                 \
                                  => This right here should be
                               ^[0-9]{1,3}(\.?)[0-9]{1,2}$

回答by Vivek Pandey

Try using like this.

尝试这样使用。

array(
    'field' => 'regex:[a-z]'
);

Hope this would helpful.

希望这会有所帮助。

回答by Thomas Kelley

Try escaping the curly braces... I bet PHP is expecting to parse a variable inside, like this:

尝试转义花括号...我敢打赌 PHP 期望解析内部的变量,如下所示:

$var = 'something';
echo 'The value is {$var}.';
// Outputs:
// The value is something.

Contrast this with:

对比一下:

$var = 'something';
echo 'The value is \{$var\}.';
// Outputs:
// The value is $var.

The part that confuses me though, is that these are within single quotes, and so this shouldn't happen. Maybe a Laravel thing?

不过让我感到困惑的部分是这些都在单引号内,所以这不应该发生。也许是 Laravel 的东西?