4webby BLOG

07 12 2007

Custom validation rules in CakePHP 1.2: the userDefined method

by Daniel | hits(4538)

TAGS: cakephp 1.2 custom validation rule models

 

How can we use custom validation rules in CakePHP 1.2?

The first way is to go straight with regular expressions, but we the using the userDefined() method of the Validation class you can define your own rules in your model, or better in the AppModel so they will be shared by all your models if needed.

 

Let's start we a small example: we want that our visitors, when posting a comment on the post of our website write at least 5 words.

 

In this example I'll put the validation rule directly in the model that uses it (instead than in the AppModel as suggested just above).

 

Ok, in our Comment model we will write:

 

class Comment extends AppModel {

var $name = 'Comment';
var $validate = array(
'content' => array('minWords'=>array('rule'=>array('userDefined', 'Comment', 'validateMinWords', 5),
'message'=>'you must write at leat 5 words',
'allowEmpty'=>false,'required' => true,
)
)
);

function validateMinWords($check, $params){

$numWords = str_word_count($check);
$condition = $numWords >= $params;

if($condition){
return true;
}
else{
return false;
}
}

 

As you can notice from the above code I tell the Comment model to validate the 'content' field against the minWords rule.

The minWords rule is "userDefined", can be found in the Comment model with the name validateMinWords, and the last parameter (5) is the minimum number of words we want.

Summarizing you should structure your validation rule as follows:



var $validate = array('field_name' => array('customRuleName'=>array('rule'=>array('userDefined', 'ModelClassName_where method_is', 'validationMethodName', eventualParameters)

This is just a quick example on how you can define custom validation rules in your models in CakePHP 1.2!

Happy baking!

Daniel

 

 


More about CakePHP 1.2 validation:

 

 

view/hide comments | add comment

  • marius

    2009-04-13 11:43:11

    Very usefull. Thank you, is exactly what i need it.

4webby.com

Tags

powered by 4webby.com