user3386779
user3386779

Reputation: 7195

custom error message for required field

I want to add custom message for the project field which is required is account field value is not 0.

Error message displaying now :The project name field is required unless account name is in 0.

I want to display as

The Project Name is Required

     $messages=[
            'project_name.required'=>'The Project Name is Required',
          ]; 
     $this->validate($request,[
     'account_name'=>'required',
     'project_name'=>'required_unless:account_name,0',
      ],$messages);

What I have to change in my code

Upvotes: 0

Views: 458

Answers (2)

There is the best way:

$rules = [
    'account_name' => 'required',
    'project_name' => 'required_unless:account_name,0',
];
$messages=[
    'project_name.required_unless' => 'The :attribute is required if the value of :other is different from the following values: :values.',
];
$attributes = [
    'project_name' => 'Project Name',
    'account_name' => 'Account Name',
];

$this->validate($request, $rules, $messages, $attributes);

The error message will be: The Project Name is required if the value of Account Name is different from the following values: 0.

The way is also compatible with required_if, required_with, same, and other rules with two attributes.

Upvotes: 0

Mortada Jafar
Mortada Jafar

Reputation: 3689

you should replace require with required_unless

$messages=[
        'project_name.required_unless'=>'The Project Name is Required',
      ]; 

laravel document:

Sometimes you may wish to specify a custom error messages only for a specific field. You may do so using "dot" notation. Specify the attribute's name first, followed by the rule

Upvotes: 2

Related Questions