Percentage or Numeric in Text Fields

Does any have a good idea, to how to restrict a field to take both percentage or numeric only in a text field? I want to allow user to enter either numeric or valid X% in the same field nothing apart from that.

You can use ‘match’ validator.

http://www.yiiframework.com/doc/guide/1.1/en/form.model#declaring-validation-rules

http://www.yiiframework.com/doc/api/1.1/CRegularExpressionValidator

You can also use beforeValidate


public function beforeValidate() {

    if(parent::beforeValidate()) {

      if (!preg_match("/^(0\.?[0-9]*|[0-100]%)$/", $this->field)) {

        $this->addError('field','field could be either float number or percentage%');

      }

      

      return true;

    }

    return false;

 }



OR as softark suggested


public function rules() {

    return array(

		//...

        array(

            'field', 

            'match', 'pattern' => '/^(0\.?[0-9]*|[0-100]%)$/',

            'message' => 'field could be either float number or 0-100 percentage%',

        ),

    );

}




If the question was about the user interface rather than validation, have a look at this nice jQuery plugin:

http://digitalbush.com/projects/masked-input-plugin