milesj / utility

[Deprecated] A CakePHP plugin for common utility classes.
MIT License
69 stars 24 forks source link

Enum: validation #11

Closed Ali1 closed 11 years ago

Ali1 commented 11 years ago

$this->enum is a pretty good method to get an array of enum key-value pairs but a method to use in $validate may also be handy. See example:

    public $validate = array(
        'country' => array(
            'checkEnum' => array(
                'rule'     => array('validateEnum'),
                'message'  => 'Please enter a valid country'
            ),
    );

Feel free to use this method which is working well for me.

    public function validateEnum($check){
        $field=key($check);
        $value=$check[$field];
        $values=$this->enum($field);
        if(empty($values)) return false;
        if(isset($values[$value])) return true;
        else return false;
    }
Ali1 commented 11 years ago

Useful when 'Security' component is turned off.

Ali1 commented 11 years ago

Tweaked to allowEmpty fields, however I'm sure there is a better way to do this which relies on 'notEmpty'=> true ?

    public function validateEnum($check,$allowEmpty=false){
        $field=key($check);
        $value=$check[$field];
        if($allowEmpty && empty($value)) return true;
        elseif(empty($value)) return false;
        $values=$this->enum($field);
        if(empty($values)) return false;
        if(isset($values[$value])) return true;
        else return false;
    }
Ali1 commented 11 years ago

Here we go!

    public function validateEnum($check,$rule){
        $field=key($check);
        $value=$check[$field];
        if(!$rule['notEmpty'] && empty($value)){
            return true; 
        }elseif(empty($value)){
            return false;
        }
        $values=$this->enum($field);
        if(empty($values)){
            return false;
        }
        if(isset($values[$value])){
            return true;
        }
        return false;
    }
milesj commented 11 years ago

So 'rule' => array('validateEnum') actually triggers the behavior method? Cool.

Don't see no reason against implementing this.

Ali1 commented 11 years ago

Exactly. I'm using it now and it's working perfectly.

On 16 July 2013 18:54, Miles Johnson notifications@github.com wrote:

So 'rule' => array('validateEnum') actually triggers the behavior method? Cool.

Don't see no reason against implementing this.

— Reply to this email directly or view it on GitHubhttps://github.com/milesj/Utility/issues/11#issuecomment-21060398 .

milesj commented 11 years ago

Added but had to change it slightly.