Custom Validation Rules in CakePHP

“Validation” you might have heard this word many times and at many places !!

Validation is basically “a process of checking correctness of something“. Validation ensures that as per our requirement, whatever we have done is correct.

For any application, data validation is one of the important aspects, it ensures that whatever data you have entered is as per the business rules of the application.

CakePHP, one of the most sought after programming languages to develop websites and web applications, has it’s own inbuilt data validation rules.

In this article I will share my knowledge about this very important part of any application, i.e. Validation. Rather I would say Custom validation.

Let’s start with a simple example, first of all as we all ( CakePHP developer ) know that any validation rule in CakePHP would always reside in the Model file of that module. So in below example we will be using User model and in that we will define our validation array as mentioned below:

1

2

3

classUserextendsAppModel{

public$validate=array();

}

Example :

Suppose we have a user table which has login and email fields, then the example below shows some simple validation rules that will apply to those fields:

1

2

3

4

5

6

classUserextendsAppModel{

public$validate=array(

'login'=>'alphaNumeric',

'email'=>'email',

);

}

Custom Validation Rules in CakePHP :

Two ways to implement custom validations in CakePHP

By Using Custom Regular Expression.

By Creating Custom Validation Methods.

1. Custom Regular Expression Validation

Regular expressions can be used to define a custom expression as a field validation rule. Suppose we have phone number and it will allow only numeric data in it. So we can write our rule like,