問題描述
假設(shè)我有兩種方法的 User
模型:
Let's say I have User
model with two methods:
User.php
class User extends Eloquent
{
/* Validation rules */
private static $rules = array(
'user' => 'unique:users|required|alpha_num',
'email' => 'required|email'
);
/* Validate against registration form */
public static function register($data)
{
$validator = Validator::make($data, static::$rules);
if($validator->fails())
{
/*... do someting */
}
else
{
/* .. do something else */
}
}
/* Validate against update form */
public static function update($data)
{
$validator = Validator::make($data, static::$rules);
if($validator->fails())
{
/*... do someting */
}
else
{
/* .. do something else */
}
}
}
我的問題:我怎樣才能讓驗證規(guī)則成為可選的,所以即使 update()
的數(shù)據(jù)只是 email
字段,它會忽略 user
并仍然驗證為 true
.
這是可能的還是我遺漏了什么?
My question: How can I make validation rules optional, so even if data for update()
would be just email
field, it would ignore user
and still validate to true
.
Is this even possible or am I missing something?
抱歉我的英語不好.
推薦答案
不確定我的問題是否正確,但如果用戶是可選的,則應(yīng)從驗證器中刪除必需".這樣你將有:
Not sure if I'm getting your question right but if the user is optional you should remove 'required' from the validator. This way you will have:
'user' => 'unique:users|alpha_num',
代替:
'user' => 'unique:users|required|alpha_num',
另一方面,我為我的模型創(chuàng)建了一個自定義方法,該方法能夠根據(jù)傳入?yún)?shù)返回自定義驗證規(guī)則.
On the other hand I create a custom method for my models that is able to return custom validation rules depending on incoming parameters.
例如:
private function getValidationRules($rules)
{
if ($rules == UPDATE_EMAIL)
{
return array('email' => 'required|email');
} else {
return array(
'user' => 'unique:users|required|alpha_num',
'email' => 'required|email'
);
}
}
我想這只是個人選擇,但我發(fā)現(xiàn)從方法中獲取驗證規(guī)則可以更好地控制我真正想要驗證的內(nèi)容,尤其是當(dāng)您想要執(zhí)行一些高級驗證時.
I guess it's only a personal choice, but I have found that getting the validation rules from a method allows more control over what I really want to validate, especially when you want to perform some advanced validations.
希望對你有幫助.
這篇關(guān)于如何使 Laravel 的 Validator $rules 成為可選?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!