How to make Laravel#39;s Validator $rules optional?(如何使 Laravel 的 Validator $rules 成为可选?)
问题描述
假设我有两种方法的 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 */
}
}
}
我的问题:我怎样才能让验证规则成为可选的,所以即使 update()
的数据只是 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?
抱歉我的英语不好.
推荐答案
不确定我的问题是否正确,但如果用户是可选的,则应从验证器中删除必需".这样你将有:
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',
另一方面,我为我的模型创建了一个自定义方法,该方法能够根据传入参数返回自定义验证规则.
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'
);
}
}
我想这只是个人选择,但我发现从方法中获取验证规则可以更好地控制我真正想要验证的内容,尤其是当您想要执行一些高级验证时.
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.
希望对你有帮助.
这篇关于如何使 Laravel 的 Validator $rules 成为可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使 Laravel 的 Validator $rules 成为可选?
基础教程推荐
- HTTP 与 FTP 上传 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01