Check user input

Hi All:

I have a normal question here.

In models ,we could use the function ‘rules’ to check user input ,

Such as this:

public function rules()

{

// NOTE: you should only define rules for those attributes that


// will receive user inputs.


return array(


	array('book_name, count', 'required'),


);

}

In my application ,I want to check it by a database value.

For example:

Database : Table name is ‘books’,an book’s count is 5. Now ,an customer buy it for 6,

All I want to do is when customer input 6, application will response a message ,tell him the book count is insufficient.

My native language is not english.I try my best to wrote this.

Thanks for help!

Hi,

you could write a custom validator, which will check the received qty value against the db:




	public function rules() {

		return array(

			...

			array('quantity', 'quantityValidator'),

			...	

		);

	}

	

	public function quantityValidator($attribute,$params) {

		$availableCount = Yii::app()->db->createCommand()

			->select($attribute)

			->from('books')

			->where('id = :id', array(':id'=>$this->id))

			->queryScalar();

		

		if ( $this->$attribute > $availableCount ) {

			$this->addError('count', 'Your error message here');

		}

	}



This solution resolved my problem!

Thanks for your help!