[英]Require custom key to register in Laravel 5
我正在处理的当前应用程序要求用户只有在获得注册密钥后才能进行注册。 在Laravel 5中,我可以将其放在Validator中:
return Validator::make($data, [
// some validation fields...
'registration_key' => 'required|same:'.$registration_key
]);
这将要求registration_key
字段与变量$registration_key
相同。 但是,一旦输入了错误的密钥,视图中的错误消息就会显示该密钥:
错误:注册密钥和[密钥值]必须匹配。
显然,我不想向用户显示密钥。 我知道Laravel有一些文档来展示如何扩展Validator外观,但是解释不充分,我无法弄清楚。 有没有人做过类似的事情并且可以帮助我?
Validator::make($data, [
// some validation fields...
'registration_key' => 'required|same:' . $registration_key
], [
'registration_key.same' => 'your text for the error message'
]);
我不知道您是否可以在请求类中声明自己的错误消息,但是可以在Controller中检查它,然后添加错误消息。
有关更多信息,请检查: http : //laravel.com/docs/5.1/validation#custom-error-messages
更新:
感谢Josh Janusch提供了更简单的解决方案
class MyRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$registration_key = 'your key';
return [
'registration_key' => 'required|same:'.$registration_key
];
}
/**
* Set custom messages for validator errors.
*
* @return array
*/
public function messages()
{
return ['registration_key.same' => 'your key is not listed'];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.