user3004356
user3004356

Reputation: 880

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

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?

Upvotes: 1

Views: 302

Answers (3)

Let me see
Let me see

Reputation: 5094

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();
}

Upvotes: 2

Alireza Fallah
Alireza Fallah

Reputation: 4607

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' );
    }
  }

Upvotes: 2

Soulgarden
Soulgarden

Reputation: 1

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();
}

Upvotes: 0

Related Questions