Laravel 4 验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16517606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 4 Validation
提问by Kevin Op den Kamp
I use the following rules for validation on creating a new user:
我使用以下规则来验证创建新用户:
protected $rules= [
'name' => 'required',
'email' => [
'required',
'unique:user',
'email'
]
];
When updating an existing user I use the same ruleset as shown above but don't want a validation error if the user didn't change his email at all.
更新现有用户时,我使用与上图相同的规则集,但如果用户根本没有更改他的电子邮件,则不希望出现验证错误。
I currently resolve this by using the following:
我目前使用以下方法解决此问题:
if (!User::changed('email')) {
unset($user->email);
}
It feels like a dirty workaround to me so I was wondering if there are better alternatives.
对我来说这感觉像是一种肮脏的解决方法,所以我想知道是否有更好的选择。
Also note that the changed
method is something I wrote myself. Does anyone know if there
is a native Laravel 4 method for checking whether a model property has changed?
另请注意,该changed
方法是我自己编写的。有谁知道是否有本地 Laravel 4 方法来检查模型属性是否已更改?
Thanks!
谢谢!
回答by Holger Weis
The unique validation rule allows to ignore a given ID, which in your case is the ID of the data set you are updating.
唯一验证规则允许忽略给定的 ID,在您的情况下,它是您正在更新的数据集的 ID。
'email' => 'unique:users,email_address,10'
回答by Orphaned Record
One approach is to create a validation function in the model and call it with the controller passing in the input, scenario and id (to ignore).
一种方法是在模型中创建一个验证函数,并通过传入输入、场景和 id(忽略)的控制器调用它。
public function validate($input, $scenario, $id = null)
{
$rules = [];
switch($scenario)
{
case 'store':
$rules = [
'name' => 'required|min:5|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required|min:4|confirmed'
];
break;
case 'update';
$rules = [
'name' => 'required|min:5|unique:users' .',name,' . $id,
'email' => 'required|email|unique:users' .',email,' . $id,
'password' => 'min:4|confirmed'
];
break;
}
return Validator::make($input, $rules);
}
Then in the controller:
然后在控制器中:
$input = Input::all();
$validation = $user->validate($input, 'update', $user->id);
if ($validation->fails())
{
// Do stuff
}
else
{
// Validation passes
// Do other stuff
}
As others mentioned, the 3rd parameter of the unique rule specifies an id to ignore. You can add other cases, such as 'login' to reuse the validation function.
正如其他人提到的,唯一规则的第三个参数指定要忽略的 id。您可以添加其他情况,例如“登录”以重用验证功能。
Alternatively, Jeffrey Way at Tuts Premium has a great series of lessons in "What's New In Laravel 4"which includes a couple of other approaches to handling validation using services and listeners.
另外,Tuts Premium 的Jeffrey Way在“Laravel 4 的新特性”中有一系列很棒的课程,其中包括使用服务和侦听器处理验证的其他几种方法。
回答by bitinn
As of 2014-01-14, you can use sometimes
attribute, I believe Taylor added them 2 days ago to Laravel 4.1
截至 2014-01-14,您可以使用sometimes
属性,我相信泰勒两天前将它们添加到 Laravel 4.1
$v = Validator::make($data, array(
'email' => 'sometimes|required|email',
));
sometimes
only validate input if it exists. this may or may not suit your exact scenario, if you don't have a default value for insert.
sometimes
仅验证输入(如果存在)。如果您没有插入的默认值,这可能适合也可能不适合您的确切情况。
http://laravel.com/docs/validation#conditionally-adding-rules
http://laravel.com/docs/validation#conditionally-adding-rules
回答by HymanPoint
See the documentation on http://four.laravel.com/docs/validation#rule-unique
请参阅http://four.laravel.com/docs/validation#rule-unique上的文档
You can exclude the users own id
您可以排除用户自己的 id
protected $rules= [
'name' => 'required',
'email' => [
'required',
'unique:user,email,THE_USERS_USER_ID',
'email'
]
];
回答by novon
I handle this sort of thing in my validator function. My validators array is setup as a class variable. I then do something like this:
我在我的验证器函数中处理这类事情。我的验证器数组设置为类变量。然后我做这样的事情:
public function validate()
{
//exclude the current user id from 'unqiue' validators
if( $this->id > 0 )
{
$usernameUnique = 'unique:users,username,'.$this->id;
$emailUnique = 'unique:users,email,'.$this->id;
$apiUnique = 'unique:users,api_key,'.$this->id;
}
else
{
$usernameUnique = 'unique:users,username';
$emailUnique = 'unique:users,email';
$apiUnique = 'unique:users,api_key';
}
$this->validators['username'] = array('required', 'max:32', $usernameUnique);
$this->validators['email'] = array('required', 'max:32', $emailUnique);
$this->validators['api_key'] = array('required', 'max:32', $apiUnique);
$val = Validator::make($this->attributes, $this->validators);
if ($val->fails())
{
throw new ValidationException($val);
}
}
回答by Martin Taleski
I have solved this by having different rules for update and create on models that need to do so, like Users.
我通过在需要这样做的模型上使用不同的更新和创建规则来解决这个问题,比如用户。
I have a Model class that extends Eloquent, where I define the validation, and then all child models that extend the Model can have have both the $rulesand $update_rulesdefined. If you define only $rules, it will be used both for create and update.
我有一个扩展 Eloquent 的模型类,我在其中定义了验证,然后所有扩展模型的子模型都可以同时定义$rules和$update_rules。如果您只定义 $rules,它将用于创建和更新。
class Model extends Eloquent {
protected $errors;
protected static $rules = array();
protected $validator;
public function __construct(array $attributes = array(), Validator $validator = null) {
parent::__construct($attributes);
$this->validator = $validator ?: \App::make('validator');
}
protected static function boot() {
parent::boot();
# call validatie when createing
static::creating(function($model) {
return $model->validate();
});
# call validatie when updating with $is_update = true param
static::updating(function($model) {
return $model->validate(true);
});
}
public function validate($is_update = false) {
# if we have $update_rules defined in the child model, and save is an update
if ($is_update and isset(static::$update_rules)) {
$v = $this->validator->make($this->attributes, static::$update_rules);
}
else {
$v = $this->validator->make($this->attributes, static::$rules);
}
if ($v->passes()) {
return true;
}
$this->setErrors($v->messages());
return false;
}
protected function setErrors($errors) {
$this->errors = $errors;
}
public function getErrors() {
return $this->errors;
}
public function hasErrors() {
return ! empty($this->errors);
}
}