我想知道如何为您的规则(例如正则表达式规则)创建您自己的错误消息,以供服务器PHP和客户端javascript重用(通过laravel-jsvalidation使用jqueryvalidation )。
我已经尝试过了,但不能让它工作,下面是一个小例子来说明我正在尝试做什么,但它不起作用。
我做错了什么?
我的小例子:
在routes\web.php文件中:
Route::get('/minimal_example_laravel_jsvalidation', function() {
// Of course these rules should not really be defined here since
// the purpose of the rules is to also reuse them from PHP Laravel code
// but my problem is now how to generate javascript that can
// reuse the same rules and therefore I just put the rules and messages
// here in this minimalistic example illustrating the problem
$rules = [
'three_digits' => 'required|regex:/^\d{3}$/'
];
$messages = [
'three_digits' => 'Must be exactly three digits'
];
$validator = JsValidator::make($rules, $messages);
return view('minimal_example_laravel_jsvalidation')->with("validator", $validator);
}); 在文件"resources\views\minimal_example_laravel_jsvalidation.blade.php":中
...
{!! $validator->selector('#myForm') !!}
...当在web浏览器中使用URL,然后“查看源代码”时,我可以看到上面的“$ http://localhost:8000/minimal_example_laravel_jsvalidation ->选择器”已经生成了以下javascript代码:
jQuery(document).ready(function(){
$("#myForm").each(function() {
$(this).validate({
errorElement: 'span',
errorClass: 'invalid-feedback',
errorPlacement: function (error, element) {
if (element.parent('.input-group').length ||
element.prop('type') === 'checkbox' || element.prop('type') === 'radio') {
error.insertAfter(element.parent());
// else just place the validation message immediately after the input
} else {
error.insertAfter(element);
}
},
highlight: function (element) {
$(element).closest('.form-control').removeClass('is-valid').addClass('is-invalid'); // add the Bootstrap error class to the control group
},
unhighlight: function(element) {
$(element).closest('.form-control').removeClass('is-invalid').addClass('is-valid');
},
success: function (element) {
$(element).closest('.form-control').removeClass('is-invalid').addClass('is-valid'); // remove the Boostrap error class from the control group
},
focusInvalid: true,
rules: {"three_digits":{"laravelValidation":[["Required",[],"The three digits field is required.",true],["Regex",["\/^\\d{3}$\/"],"The three digits format is invalid.",false]]}} });
});
});实际上,当我没有通过web浏览器在字段中输入三位数时,我得到的错误消息是上面的“三位数格式无效”。虽然我希望它应该是我在"$messages“数组中定义的”必须恰好是三位数“。
我已经看到,可以使用Laravel创建带有“自定义验证规则”的PHP类,其中还可以定义自定义消息,但据我所知,如果您将这些自定义规则与laravel-jsvalidation一起使用,则必须使用AJAX而不是直接在浏览器中进行javascript验证,这是我想要做的,而不是进行AJAX调用。
我正在使用以下版本:
laravel/framework v7.4.0
proengsoft/laravel-jsvalidation 3.0.0
发布于 2020-05-24 06:20:33
尝试像这样更改消息数组,
$messages = [
'three_digits.required' => 'Three Digits field is required',
'three_digits.regex' => 'Must be exactly three digits'
];请注意,我还向message键添加了规则。('three_digits.required')
https://stackoverflow.com/questions/61033992
复制相似问题