Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Custom Validation rules in CakePHP

    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 656
    Comment on it

    Validation is a process of analyzing the exactness of data. It assures that the data entered is according to our requirement or not.

    CakePHP has it's own inbuilt validation rules. In CakePHP validation rule is locate in the Model file of that particular module.

    Syntax:

    class User extends AppModel {
     		public $validate = array();
    }

    In the example below we will use user model for the validation:

    class User extends AppModel {
    	public $validate = array(
    		'login' => 'alphaNumeric',
    		'email' => 'email',
    	);
    }
    

     

    There are two ways to implement custom validation:-

    • By Using Custom Regular Expression
    • By Creating Custom Validation Methods.

     

    1. By using Custom Regular Expression:-  In this regular expressions are used to validate the date.

     

    Example to validate user name-

    'username' => array(
    	'rule' => array(
    	'rule'    => '/^[a-z0-9]{3,}$/i',
    	'message' => 'letters and integers allowed of minimum 3..!',
    	),
    )

     

    2. By creating Custom Validation Methods:-  In this we can define validation according to our need.

    Example to check the uniqueness of email-

    class User extends AppModel {
    	public $validate = array(
           	'username' => array(
    	
    			'unique' => array(
    				'rule'    => array('isUnique'),
    				'message' => 'This username is already in use, pl provide another username'
    			),
    			
    		)
    	);
     
    	function isUnique($check) {
    	// First it will fetch the username from database and it will check for its uniqueness.
    		$username = $this->find('first',array(
                    'fields' => array(
                        'User.id',
                        'User.username'
                    ),
                    'conditions' => array(
                        'User.username' => $check['username']
                    )
                )
            );

     

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: