Using special form validation formulas

Using Laravel localization ( http://laravel.com/docs/5.1/localization ) I created some custom validation attributes to provide more friendly validation errors (like "Name" instead of name, etc.).

I use form requests ( http://laravel.com/docs/5.1/validation#form-request-validation ) to check user data and there are scripts in which I would like to provide storage (for example, I can have a field “name”, which is a trade name in one context and a product name in another).

The messages () method allows me to specify certain rules for overriding the verification rules, but this is not ideal, since this is not a verification message as such, we must redefine just the attribute name (for example, if we have 5 validations of the rule for "email", we should provide 5 overrides here, not one override for, say, the client’s email).

Is there a solution? I mark the links to formatValidationErrors () and formatErrors () in the Laravel documentation, but there really is no information on how to redefine them correctly, and I'm not very lucky.

+4
source share
2 answers

You can override attribute names that default to the field name.

With a form request

attributes():

public function attributes()
{
    return [
        'this_is_my_field' => 'Custom Field'
    ];
}

4- :

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

Validator::make($data, $rules, $messages, $customAttributes);

Route::get('/', function () {
    // The data to validate
    $data = [
        'this_is_my_field' => null
    ];

    // Rules for the validator
    $rules = [
        'this_is_my_field' => 'required',
    ];

    // Custom error messages
    $messages = [
        'required' => 'The message for :attribute is overwritten'
    ];

    // Custom field names
    $customAttributes = [
        'this_is_my_field' => 'Custom Field'
    ];

    $validator = Validator::make($data, $rules, $messages, $customAttributes);

    if ($validator->fails()) {
        dd($validator->messages());
    }

    dd('Validation passed!');
});
+7

, (http://laravel.com/docs/5.1/validation#form-request-validation) .

Laravel - rules() authorize(). , messages() , attributes(), :

public function attributes()
{
     return [
         'name' => 'Product Name'
     ]
}

.

+3

All Articles