Laravel custom messages for array validation

后端 未结 10 2453
南笙
南笙 2021-02-20 05:36

I am having a form and I have an array of input fields for video urls, now when I validate form if I have multiple invalid fields with video urls, I get the same message for eac

相关标签:
10条回答
  • 2021-02-20 06:19

    To use a custom messages from outside the validation language file, you can use it this way:

    $messages = ['username.required' => 'customeError'];
    
    $validator = \Validator::make(
        $data,
        ['username' => 'required'],
        messages
    );
    

    You can just pass an array of your custom messages as the third parameter as I have used it above. Hope this helps.

    0 讨论(0)
  • 2021-02-20 06:19

    For laravel 7.x, I have found the following solution. You can basically use 'field.rule' => 'message'

    public function rules() 
    {
       return [
          'user.*.firstname' => 'string|required',
       ];
    }
    

    And then in the messages (I use a FormRequest for all requests):

    public function messages() 
    {
       'user.*.firstname.required' => 'Firstname of the user is required',
    }
    

    You can also pass a translation string like 'passwords.user' to the message.

    0 讨论(0)
  • 2021-02-20 06:20

    I think this will help you if you are using "name=location[]" this in your view page.

     for ($i = 0; $i <= sizeof($location); $i++) {
     $this->validate($request,
     [
    // set the rules
      'location.'.$i => 'required',
      'contact_no.'.$i => 'required',
       'email.'.$i => 'required|email',
     ], 
    [
    // set your custom error messages here 
      'location.'.$i.'.'.'required' => 'Contact no. is required', 
      'contact_no.'.$i.'.'.'required' => 'Contact no. is required',
      'email.'.$i.'.'.'required' => 'Email is required',
      'email.'.$i.'.'.'email' => 'Please enter valid email address'
    ]);
    }
    
    0 讨论(0)
  • 2021-02-20 06:22
    'external_media.*.required' => 'active_url',
    
    0 讨论(0)
提交回复
热议问题