Numeric Range validator extension

Hi. I had a need for a numeric range validator extension that would also do client side js validation, and cRangeValidator checks that the value exists in a preset range, not using >< operators on numeric values.

I coded this very simple extension based on the create your own validation rule tutorial here: http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/

The extension code below should go in extensions/validators/numericRange.php (create the file and paste it in)




<?php


class numericRange extends CValidator

{

 

    public $min;

    public $max;


    /**

     * Validates the attribute of the object.

     * If there is any error, the error message is added to the object.

     * @param CModel $object the object being validated

     * @param string $attribute the attribute being validated

     */

    protected function validateAttribute($object,$attribute)

    {

     

        // extract the attribute value from it's model object

        $value=$object->$attribute;

        

        if (($value < $this->min) || ($value > $this->max)) 

        {

            $this->addError($object,$attribute,'Value out of range.');

        }

    }

    

    /**

     * Returns the JavaScript needed for performing client-side validation.

     * @param CModel $object the data object being validated

     * @param string $attribute the name of the attribute to be validated.

     * @return string the client-side validation script.

     * @see CActiveForm::enableClientValidation

     */

    public function clientValidateAttribute($object,$attribute)

    {

        

         

        $condition="(value < ".$this->min.") || (value > ".$this->max.")";

     

        return "

    if(".$condition.") {

        messages.push(".CJSON::encode('Value out of range.').");

    }

    ";

    }


}

?>



then you can use it in any model:




public function rules()

	{

	return array(

            // validate that a number falls within specified range, I'm using 0-100 for percent

            array('my_percent_field_to_validate', 'ext.validators.numericRange', 'min'=>0, 'max'=>100),

            // .... //

	);

	}

Maybe it will save someone else some time…

Hello, thanks for sharing. Isn’t it like CNumberValidator?

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

I figured there was already something that would do this (or at least was hoping) but my searches for for "validate numeric range" kept turning up only cRangeValidator. Good to know numberValidator does this. I thought it just validated that your number was a number.

Cool :)

edit >

I noticed actually that CNumberValidator documentation page right at the top says "CNumberValidator validates that the attribute value is a number. "

That probably also threw me off.

Thanks for the tip though.