如何验证要在 Yii 中填写的任一文本字段 [英] How can validate either one of the textfields to be filled in Yii

查看:25
本文介绍了如何验证要在 Yii 中填写的任一文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Yii 框架的新手.现在在我的表单中,我有两个字段 FirstName 和 LastName.我想验证是否填充了两者中的任何一个.即不是两者都应该是空的.假设用户将两个字段都留空,则不应允许提交.用户至少应输入这些字段中的任何一个.
规则

I'm new to Yii framework. Now in my form I have two fields FirstName and LastName. I want to validate such that either of the two is filled. i.e not both should be empty. Suppose the user leaves both the fields empty it should not allow submit. The user should atleast enter any of these fields.
Rules

public function rules()
        {
                return array(

                        array('Firstname,Lastname, email, subject, body', 'required'),
                        array('email', 'email'),
                        array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
                );
        }

我该怎么做?

推荐答案

你可以使用 beforeValidate() 来解决这个问题在你的模型中创建一个方法

You can use beforeValidate() for this In your model make a method

public function beforeValidate()
{
$firstName=trim($this->firstName);
$lastName=trim($this->lastName);
if(empty($firstName) && empty($lastName))
{
$this->addError('firstName','Please Enter your name');
}
return parent::beforeValidate();
}

这篇关于如何验证要在 Yii 中填写的任一文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆