Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • CakePHP Form Validation Using Ajax

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.24k
    Comment on it

    As we know cakephp have not any kind of in-build form validater to check requried fields. So by ajax we can check form validation.

    The flow is that first of all we have to submit the form via ajax to controller and check the validation throw cakephp validation checker function. When you fire it then validation error will return and then you can manage it by jqeury under ajax success function.

    1. Modal Validation Rules
        class User extends AppModel{
            var $name = 'User';
            var $useTable = false;
            var $validate = array(
                'first_name' => array(
                    'rule' => 'notEmpty',
                    'message' => 'You have not entered First name.'
                'last_name' => array(
                    'rule' => 'notEmpty',
                    'message' => 'You have not entered Last name.'
    1. Check validation in controller
    class UsersController extends AppController{
        var $name = 'User';
          var $uses = 'User';
        public function saveData(){
            if($this->User->validates()) {
                //$this->redirect(array('controller'=>'Pages', 'action'=>'display'));
                $invalidFields     =   $this->User->invalidFields();
                echo json_encode($invalidFields);
    1. View page html
        echo $this->Form->create('User', array('url'=>array('action'=>'saveData')));
        echo $this->Form->input('User.first_name', array('required'=>false, 'class'=>'first_name'));
        echo $this->Form->input('User.last_name', array('required'=>false, 'class'=>'last_name'));
        echo $this->Form->button('Save', array('id'=>'save'));
        echo $this->Form->end();
    1. View page ajax
                var returnCheck =   false;
                    type    :   'POST',
                    url     :   '<?php echo Router::url(array("controller"=>"Users", "action"=>"saveData")); ?>',
                    data    :   $(this).serialize(),
                    dataType:   'json',
                    async   :   false,
                    success :   function(validationResponse){
                        if(validationResponse != ''){
                            $.each(validationResponse, function(fieldName, message){
                                $('.'+fieldName).after('<div class="error">'+message[0]+'</div>');
                            returnCheck =   true;
                    error   :   function(jqXHR, textStatus, errorThrown){
                return returnCheck;

 0 Comment(s)

Sign In

Sign up using

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: