简体   繁体   English

自定义 Laravel 验证消息

[英]Custom Laravel validation messages

I'm trying to create customized messages for validation in Laravel 5. Here is what I have tried so far:我正在尝试在 Laravel 5 中创建用于验证的自定义消息。这是我到目前为止所尝试的:

$messages = [
    'required'  => 'Harap bagian :attribute di isi.',
    'unique'    => ':attribute sudah digunakan',
];
$validator = Validator::make($request->all(), [
    'username' => array('required','unique:Userlogin,username'),
    'password' => 'required',
    'email'    => array('required','unique:Userlogin,email'),$messages
]);

if ($validator->fails()) { 
    return redirect('/')
        ->withErrors($validator) // send back all errors to the login form
        ->withInput();
} else {
    return redirect('/')
        ->with('status', 'Kami sudah mengirimkan email, silahkan di konfirmasi');   
}   

But it's not working.但它不起作用。 The message is still the same as the default one.该消息仍与默认消息相同。 How can I fix this, so that I can use my custom messages?我该如何解决这个问题,以便我可以使用我的自定义消息?

Laravel 5.7.* Laravel 5.7.*

Also You can try something like this.你也可以尝试这样的事情。 For me is the easiest way to make custom messages in methods when you want to validate requests:对我来说,当您想验证请求时,在方法中制作自定义消息的最简单方法:

public function store()
{
    request()->validate([
        'file' => 'required',
        'type' => 'required'
    ],
    [
        'file.required' => 'You have to choose the file!',
        'type.required' => 'You have to choose type of the file!'
    ]);
}

If you use $this->validate() simplest one, then you should write code something like this..如果你使用$this->validate()最简单的一个,那么你应该写这样的代码。

$rules = [
        'name' => 'required',
        'email' => 'required|email',
        'message' => 'required|max:250',
    ];

    $customMessages = [
        'required' => 'The :attribute field is required.'
    ];

    $this->validate($request, $rules, $customMessages);

You can provide custom message like :您可以提供自定义消息,例如:

$rules = array(
            'URL' => 'required|url'
        );    
$messages = array(
                'URL.required' => 'URL is required.'
            );
$validator = Validator::make( $request->all(), $rules, $messages );

if ( $validator->fails() ) 
{
    return [
        'success' => 0, 
        'message' => $validator->errors()->first()
    ];
}

or要么

The way you have tried, you missed Validator::replacer() , to replace the :variable您尝试过的方式,您错过了Validator::replacer()来替换:variable

Validator::replacer('custom_validation_rule', function($message, $attribute, $rule, $parameters){
    return str_replace(':foo', $parameters[0], $message);
});

You can read more from here and replacer from here你可以阅读更多从这里和替代品从这里

For Laravel 8.x , 7.x , 6.x对于 Laravel 8.x , 7.x , 6.x
With the custom rule defined, you might use it in your controller validation like so :定义自定义规则后,您可以在控制器验证中使用它,如下所示:

$validatedData = $request->validate([
       'f_name' => 'required|min:8',
       'l_name' => 'required',
   ],
   [
    'f_name.required'=> 'Your First Name is Required', // custom message
    'f_name.min'=> 'First Name Should be Minimum of 8 Character', // custom message
    'l_name.required'=> 'Your Last Name is Required' // custom message
   ]
);

For localization you can use :对于本地化,您可以使用:

['f_name.required'=> trans('user.your first name is required'],

Hope this helps...希望这可以帮助...

$rules = [
  'username' => 'required,unique:Userlogin,username',
  'password' => 'required',
  'email'    => 'required,unique:Userlogin,email'
];

$messages = [
  'required'  => 'The :attribute field is required.',
  'unique'    => ':attribute is already used'
];

$request->validate($rules,$messages);
//only if validation success code below will be executed
//Here is the shortest way of doing it.
 $request->validate([
     'username' => 'required|unique:Userlogin,username',
     'password' => 'required',
     'email'    => 'required|unique:Userlogin,email'
 ],
 [
     'required'  => 'The :attribute field is required.',
     'unique'    => ':attribute is already used'
 ]);
//The code below will be executed only if validation is correct.

You can also use the methods setAttributeNames() and setCustomMessages() , like this:您还可以使用setAttributeNames()setCustomMessages() ,如下所示:

$validation = Validator::make($this->input, static::$rules);

$attributeNames = array(
    'email' => 'E-mail',
    'password' => 'Password'
);

$messages = [
    'email.exists' => 'No user was found with this e-mail address'
];

$validation->setAttributeNames($attributeNames);
$validation->setCustomMessages($messages);

For those who didn't get this issue resolve (tested on Laravel 8.x):对于那些没有解决这个问题的人(在 Laravel 8.x 上测试):

$validated = Validator::make($request->all(),[
   'code' => 'required|numeric'
  ],
  [
    'code.required'=> 'Code is Required', // custom message
    'code.numeric'=> 'Code must be Number', // custom message       
   ]
);

//Check the validation
if ($validated->fails())
{        
    return $validated->errors();
}
    $rules = [
        'name' => 'required',
        'email' => 'required|email',
        'message' => 'required|max:250',
    ];

    $customMessages = [
        'required' => 'The :attribute field is required.',
        'max' => 'The :attribute field is may not be greater than :max.'
    ];

    $this->validate($request, $rules, $customMessages);

run below command to create a custom rule on Laravel运行以下命令以在 Laravel 上创建自定义规则
ı assuming that name is CustomRule我假设名称是 CustomRule

php artisan make:rule CustomRule

and as a result, the command was created such as PHP code结果,该命令被创建,例如PHP代码

if required keyword hasn't on Rules,That rule will not work如果 required 关键字没有在规则上,该规则将不起作用

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class CustomRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        //return  true or false
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The validation error message.';
    }
}


and came time using that first, we should create a request class if we have not并首先使用它,如果我们还没有,我们应该创建一个请求类

php artisan make:request CustomRequest

CustomRequest.php自定义请求.php

<?php


namespace App\Http\Requests\Payment;

use App\Rules\CustomRule;
use Illuminate\Foundation\Http\FormRequest;

class CustomRequest extends FormRequest
{


    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(): array
    {
        return [
            'custom' => ['required', new CustomRule()],
        ];
    }

    /**
     * @return array|string[]
     */
    public function messages(): array
    {
        return [
            'custom.required' => ':attribute can not be empty.',
        ];
    }
}

and on your controller, you should inject custom requests to the controller在您的控制器上,您应该向控制器注入自定义请求

your controller method你的控制器方法

class FooController
{
    public function bar(CustomRequest $request)
    {
        
    }
}

In the case you are using Request as a separate file:如果您使用 Request 作为单独的文件:

 public function rules()
 {
    return [
        'preparation_method' => 'required|string',
    ];
 }

public function messages()
{
    return [
        'preparation_method.required' => 'Description is required',
    ];
}

Tested out in Laravel 6+在 Laravel 6+ 中测试

you can customise the message for different scenarios based on the request.您可以根据请求自定义不同场景的消息。

Just return a different message with a conditional.只需返回带有条件的不同消息。


<?php

namespace App\Rules;

use App\Helpers\QueryBuilderHelper;
use App\Models\Product;
use Illuminate\Contracts\Validation\Rule;

class ProductIsUnique implements Rule
{

    private array $attributes;
    private bool $hasAttributes;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct(array $attributes)
    {
        $this->attributes = $attributes;
        $this->hasAttributes = true;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $brandAttributeOptions = collect($this->attributes['relationships']['brand-attribute-options']['data'])->pluck('id');

        $query = Product::query();

        $query->when($brandAttributeOptions->isEmpty(), function ($query) use ($value) {
            $query->where('name', $value);
            $this->hasAttributes = false;
        });

        
        return !$query->exists();
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return ($this->hasAttributes) ? 'The Selected attributes & Product Name are not unique' : 'Product Name is not unique';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM