The use of the $message parameter is mentioned in validate to define the error message for validation,

message variable

Error message $message variable supports:

  • :attribute Indicates field name
  • {:field} Indicates field content

TIP

The above text is supported in custom rules using

:attribute

:attribute represents the name of the field in the customAttributes variable that currently triggers the error:

class Test extends Validate
{
    protected $rule = [
        'user' => 'required'
    ];
    
    protected $message = [
        'user.required' => 'Please fill in the :attribute'
    ];
    
    protected $customAttributes = [
        'user' => 'account'
    ];
}







 






1
2
3
4
5
6
7
8
9
10
11
12
13
14

After triggering, the message prompted is Please fill in the account

{:field}

The field in the middle of {:field} is the field of the current validation value. If the specified field does not exist, it is empty text, support for getting an array, such as info.name, on behalf of getting the name parameter in the info array. supports unlimited depth.

class Test extends Validate
{
    protected $rule = [
        'name' => 'chs'
    ];
    
    protected $message = [
        'name.chs' => 'The name you filled in {:name} is not a Chinese name'
    ];
}







 


1
2
3
4
5
6
7
8
9
10

Enter data ['name' => 'Rasmus Lerdorf'],prompt:The name you filled in Rasmus Lerdorf is not a Chinese name

@{field}

@{field} means use the custom name of field

class User extends Validate
{
    protected $rule = [
        'pass'   => 'required',
        'repass' => 'required|same:pass'
    ];

    protected $customAttributes = [
        'pass'   => 'Password',
        'repass' => 'Confirm Password'
    ];

    protected $message = [
        'repass.same' => ':attribute and @{pass} do not match'
    ];
}













 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

The last error message triggered is:Confirm Password and Password do not match

customAttributes variable

When we define many validation fields and rules, it would take a lot of time and cost to write error messages one by one correspondingly. At this time, we can use the $customAttributes variable to define the names of the fields.

Automatically replaces the :attribute text in the default error message when the error is triggered

class User extends Validate
{
    protected $rule = [
        'id' => 'required|numeric',
    ];

    protected $customAttributes = [
        'id' => 'User ID',
    ];
}






 
 
 

1
2
3
4
5
6
7
8
9
10

When the error is triggered, it will prompt User ID is required

{:field} is also supported in the customAttributes variable, e.g:

protected $customAttributes = [
    'id' => 'User ID:{:id}',
];

 

1
2
3

If the id is passed in as hello At this point the trigger will prompt User ID: hello must be a number.

Last Updated: 6/16/2021, 7:51:54 PM