Search code examples
phplaravellocalizationlaravel-validationlaravel-localization

Validating Password rules with a custom error message


Using standard notation like "password.required" I can customize an error message for built-in validation rules. But how can I customize error messages for Illuminate\Validation\Rules\Password rules?

$rules = [
    'password' => [
        'required',
        'confirmed',
        Rules\Password::min(8)->letters()->mixedCase()->numbers()->symbols(),
    ],
];
$messages = [
    'password.required'  => 'يجب ادخال كلمة المرور',
    'password.confirmed' => 'كلمة المرور غير متطابقة',
];
$request->validate($rules, $messages);

How to customize the messages for min(), letters(), etc?


Solution

  • According to this comment in the original pull request, you can't do this in code, and have to use the JSON localization files.

    So check the validation class for the default text and then in resources/lang/ar.json add a translation for it, like so:

    {
      "The :attribute must contain at least one letter.": ":attribute يجب أن يحتوي على الأقل حرف واحد.",
      "The :attribute must contain at least one uppercase and one lowercase letter.": ":attribute يجب أن يحتوي على الأقل حرف كبير واحد وحرف صغير واحد.",
      "The :attribute must contain at least one number.": ":attribute يجب أن يحتوي على الأقل رقم واحد.",
      "The :attribute must contain at least one symbol.": ":attribute يجب أن يحتوي على الأقل رمز واحد."  
    }
    

    The length message uses the standard one found in resources/lang/ar/validation.php:

    <?php
    return [
      "min" => [
        "string" => "يجب أن يكون طول نص حقل :attribute على الأقل :min حروفٍ/حرفًا.",
      ],
    ];
    

    Or it can be declared in your code above.

    $messages = [
        'password.required'  => 'يجب ادخال كلمة المرور',
        'password.confirmed' => 'كلمة المرور غير متطابقة',
        'password.min' => 'whatever',
    ];
    

    Note there are packages such as Laravel Lang that can do all these translations for you.