问题
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()),
);
}
How can I do this?
回答1:
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();
}
回答2:
public function rules()
{
return array(
array('Firstname,Lastname', 'oneOfTwo', 'Firstname', 'Lastname'),
);
}
public function oneOfTwo($attribute,$params)
{
$valid = false;
foreach ($params as $param) {
if ($this->$param !== NULL) {
$valid = true;
break;
}
}
if ($valid === false) {
$this->addError( $attribute, 'Your error message' );
}
}
回答3:
In model
public function rules() {
return array(
array('field1, field2', 'required')
);
}
Action in controller
$model = new Model;
if (!empty($_POST['Model'])) {
$model->attributes = Yii::app()->request->getPost('Model');
if ($model->validate())
$model->save();
}
来源:https://stackoverflow.com/questions/21425672/how-can-validate-either-one-of-the-textfields-to-be-filled-in-yii