简体   繁体   English

使用 Rule::in 作为验证时如何添加自定义 Laravel 错误消息

[英]How to add a custom Laravel error message when using Rule::in as validation

I am validating a select dropdown in Laravel with an array of agency names.我正在使用一组机构名称验证 Laravel 中的 select 下拉列表。 I am using Rule::in() to do this.我正在使用 Rule::in() 来执行此操作。 The validation works well and I am getting the standard error message back 'The selected agency-name is invalid'.验证效果很好,我收到了标准错误消息“所选机构名称无效”。 I want to edit this into a custom error message but am having difficulty doing this the same way as I have before.我想将其编辑为自定义错误消息,但很难以与以前相同的方式执行此操作。 Here is my code.这是我的代码。

$agencies = Session::get('config.agency-names');
    $agency_names = array();
    for ($x = 0; $x < count($agencies['Agencies']); $x++) {
        $name = $agencies['Agencies'][$x]["AgencyName"];
        array_push($agency_names, $name);
        array_push($agency_names, '');
    }

$request->validate([
        'referral'    => 'required',
        'agency-name' => ['required_if:referral,no', Rule::in($agency_names)],
        'password'    => 'required|min:6|regex:/[A-Z]/|regex:/[a-z]/|regex:/[0-9]/|confirmed'], [
        // New custom agency name message
        agency-name.Rule::in(agency_names) => 'NEW MESSAGE (DOESN\'T WORK)',
        // Custom password messages.
        'password.confirmed' => 'Confirmation password did not match, please try again.',
        'password.regex'     => 'Password does not meet criteria, Please try again.',
        'password.min'       => 'Password does not meet criteria, please try again.',
]);

in validate method, you have two parameters, one for the fields input and the other for validation messages.validate方法中,您有两个参数,一个用于字段输入,另一个用于验证消息。

validation messages are called according to the validation rules with validation type, using Rule object doesn't change that.验证消息根据具有验证类型的验证规则调用,使用规则 object 不会改变这一点。

in your code you had to add 'agency-name.in' just like when you use in validation在您的代码中,您必须添加“agency-name.in”,就像您in验证中使用时一样

$request->validate([
        'referral'    => 'required',
        'agency-name' => ['required_if:referral,no', Rule::in($agency_names)],
        'password'    => 'required|min:6|regex:/[A-Z]/|regex:/[a-z]/|regex:/[0-9]/|confirmed'], [
        // New custom agency name message
       'agency-name.in' => 'NEW MESSAGE ',
        // Custom password messages.
        'password.confirmed' => 'Confirmation password did not match, please try again.',
        'password.regex'     => 'Password does not meet criteria, Please try again.',
        'password.min'       => 'Password does not meet criteria, please try again.',
]);

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

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