Find us on facebook

Oct 12, 2013

Create a form with Yii (Part 2 - Declaring Validation Rules in Model Class)

When the user submit inputs we need to check whether the inputs are valid. For doing that we need to do validation. We can write code for validation rules inside rules() function which is located in Customer model class we created in Create a form with Yii (Part 1 - Define Model class). This function will return an array with rule configurations.

we should only define rules for the attributes that will receive user inputs.

public function rules() {
     
        return array(
            array('id, title_id, first_name, last_name, gender, dob, city, state, postal_code, phone, mobile_phone, email, marital_status', 'required'),
            array('title_id', 'numerical', 'integerOnly' => true),
            array('city, state, postal_code,mobile_phone, marital_status', 'length', 'max' => 20),
            array('first_name, last_name,email', 'length', 'max' => 50),
            array('gender', 'length', 'max' => 2),
            array('phone', 'length', 'max' => 30),
            array('email', 'email', 'checkMX' => true),
            array('dob', 'safe'),
            array('id, title_id, first_name, last_name,gender, dob,city, state, postal_code,phone, mobile_phone, email, marital_status', 'safe', 'on' => 'search'),
        );
    }

We will check the code line by line.

1)
array('id, title_id, first_name, last_name, gender, dob, city, state, postal_code, phone, mobile_phone, email, marital_status', 'required')
This code specifies that "id, title_id, first_name, last_name, gender, dob, city, state, postal_code, phone, mobile_phone, email, marital_status" these all attributes are required.

2)
array('title_id', 'numerical', 'integerOnly' => true)
This specifies that title_id is numerical and it's value must be integer.

3)
array('city, state, postal_code,mobile_phone, marital_status', 'length', 'max' => 20)
This code says that above mentioned attributes' maximum lenghth should be 20 characters.

4)
array('email', 'email', 'checkMX' => true)
checks if the email has a MX(mail exchanger record) registered

5)
array('dob', 'safe')
If a field has no particular data-format validations, we use 'safe' validator(This will be discussed clearly later).

4)
array('id, title_id, first_name, last_name,gender, dob,city, state, postal_code,phone, mobile_phone, email, marital_status', 'safe', 'on' => 'search')
In search scenario

No comments:

Post a Comment