How can validate either one of the textfields to be filled in Yii

爷,独闯天下 提交于 2021-01-28 06:46:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!