CakePHP: Custom validation rule in model

Data validation is very important part of any application. CakePHP has its own validation rules to validate data like alphaNumeric, email, numeric.

Let’s start with simple example using inbuilt validation rules. As you know, we have to define our validation rules in a public $validate variable in our model. We have a User model and we want to apply validation rules on email and password fields,

When we save data using User->save() method, it will validate data against our rules. If it matches, it will allow saving data otherwise it will return validation errors.

This was about using core validation rules and how to apply them. Now what if we don’t find any core validation rule that fulfill our requirements? How to validate those data?

CakePHP provides custom validation rules, we can define our own rules and use them in validation.

Custom validation rules

There are 2 ways to apply custom validation rules:

    1. Using a regular expression
    2. Using our own validation methods

1. Using a regular expression

If we have a regular expression that validates our da, we can use that directly as rule. For example,

Above validation rule checks if the username contains alphabets only.

2. Using our own validation methods

We can define our own validation method to validate the data. For example, to check whether username contains letters, numbers, dash and underscore only. See below code,

 

Here, we can use arguments also in our validation method. For example, to check the length of username with above validation rule, we can use the limit as an argument,

This is how we can use custom validation rules in CakePHP, simple and easy.

You may also like...