Yii2 中的模型形式规则和验证
Model form rules and validation in Yii2
例如我有模型形式 MySubmitForm
:
use yii\base\Model;
class MySubmitForm extends Model{
public $value1;
public $value2;
public $value3;
public function rules(){
return [['value1', 'value2'],'required'];
}
}
这里我有两个必需的参数($value1
、$value2
),我希望其中之一是 必需的 或者我希望用户得到错误仅当 $value1
和 $value2
都为空时。
我可以从这个表单模型中实现吗?
您可以在验证规则中使用自定义验证函数。
可能的选项:
1) Select最重要的相关字段并添加错误。
2) Select 多个重要的相关字段并向它们添加相同的错误消息(我们可以在传递之前将消息存储和传递在单独的变量中以保留代码干).
3) 我们可以使用不存在的属性名称来添加错误,比方说 all
因为此时不检查属性是否存在。
public function rules()
{
return [['value1', 'value2'],'yourCustomValidationMethod'];
}
public function yourCustomValidationMethod()
{
// Perform custom validation here regardless of "name" attribute value and add error when needed
if ($this->value1=='' && $this->value2=='') {
//either use session flash
Yii::$app->session->setFlash('error','You need to provide one of the fields');
//or use model error without any specific field name
$this->addError('all', 'Your error message');
}
}
请注意,您可以使用 session flash
或 model
来通知您喜欢的错误使用方式
例如我有模型形式 MySubmitForm
:
use yii\base\Model;
class MySubmitForm extends Model{
public $value1;
public $value2;
public $value3;
public function rules(){
return [['value1', 'value2'],'required'];
}
}
这里我有两个必需的参数($value1
、$value2
),我希望其中之一是 必需的 或者我希望用户得到错误仅当 $value1
和 $value2
都为空时。
我可以从这个表单模型中实现吗?
您可以在验证规则中使用自定义验证函数。
可能的选项:
1) Select最重要的相关字段并添加错误。
2) Select 多个重要的相关字段并向它们添加相同的错误消息(我们可以在传递之前将消息存储和传递在单独的变量中以保留代码干).
3) 我们可以使用不存在的属性名称来添加错误,比方说 all
因为此时不检查属性是否存在。
public function rules()
{
return [['value1', 'value2'],'yourCustomValidationMethod'];
}
public function yourCustomValidationMethod()
{
// Perform custom validation here regardless of "name" attribute value and add error when needed
if ($this->value1=='' && $this->value2=='') {
//either use session flash
Yii::$app->session->setFlash('error','You need to provide one of the fields');
//or use model error without any specific field name
$this->addError('all', 'Your error message');
}
}
请注意,您可以使用 session flash
或 model
来通知您喜欢的错误使用方式