Laravel自定义验证消息 [英] Laravel custom validation messages
问题描述
我正在尝试使用Laravel
验证英国邮政编码.这就是我所拥有的:
I'm trying to validate a UK postcode using Laravel
. Here's what I've got:
//routes.php
$rules = array(
'pcode' => array('required:|Regex:/^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$/')
);
$messages = array(
'required' => 'The :attribute field is required.',
'pcode' => array('regex', 'Poscode should be a valid UK based entry'),
);
$validator = Validator::make(Input::all(), $rules, $messages);
在我的blade
中:
<input id="postcode" name="pcode" value="{{Input::old('pcode')}}" type="text" placeholder="Postcode" class="form-control" xequired="" />
@if( $errors->has('pcode') ) <span class="error" style='background-color: pink;'>{{ $errors->first('pcode') }}</span> @endif
如果我提交的表单中的pcode
字段为空,则会警告我输入必填字段.如果我输入了无效的邮政编码"74rht",则我的验证器没有执行任何操作或无法显示上述自定义消息?
If I submit the form with an empty pcode
field, it warns me for a required field. If I enter an invalid postcode, '74rht' say, my validator does nothing or fails to display my custom message as defined above?
推荐答案
Laravel 手册状态:
The Laravel manual states:
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.
将$rules
更改为以下结构:
$rules = array(
'pcode' => array(
'required',
'Regex:/^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$/'
)
);
如果这不起作用,则可能是您的正则表达式无效,请尝试使用更简单的正则表达式来检查验证程序是否有效.
If that doesn't work, then maybe your regex isn't valid, try to use a easier regex to check if the validator works.
这篇关于Laravel自定义验证消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!