Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use Validation in CakePHP using Ajax in 2.4.1 version?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 482
    Comment on it

    Hi Reader's,
    Welcome to FindNerd,today we are going to discuss how to use Validation in CakePHP using Ajax in 2.4.1 version?
    Validation is very important feature for user input in a web application. By validation we can make sure that the data input by the user is correct or not.

    In cakephp there is not any kind of in-build form validator for checking required fields. So we can use ajax for checking validation in our web application.

    For example, in a web application we have to use registration form and we have multiple different input fields like, username, password and we want to validate all input fields which is given below.
    1-Username:-Username should be required and not null.
    2-Password:-Passwords should be at least eight characters long or more and not null.

    So, for making data validation the first step will be to create the validation rules in the Model.
    Modal Validation Rules

    <?php
        class User extends AppModel{
          var $name = 'User';
          var $useTable = false;
          var $validate = array(
            'username' => array(
            'rule' => 'notEmpty',
            'message' => 'Username must be filled.'
            ),
            'passwoed' => array(
            'rule' => 'notEmpty',
            'message' => 'Password must be 8 disit.'
            ) 
          );
        }
    
    ?>

    Now we have to submit the form via ajax to controller and check the validation through CakePHP validation.
    Check validation in controller

    <?php
      class UsersController extends AppController{
        var $name = 'User';
        var $uses = 'User';
        public function saveData(){
          $this->User->set($this->request->data);
          if($this->User->validates()) {
           $this->redirect(array('controller'=>'Pages', 'action'=>'display'));
          }else{
             $invalidFields = $this->User->invalidFields();
             echo json_encode($invalidFields);
            }
          exit;
        }
      }
    ?> 

    When you fire it then validation error will return and then you can manage it by jQuery under ajax success function.

    firstly let see view page 

    <?php
     <div id="UserForm">
        echo $this->Form->create('User', array('url'=>array('action'=>'saveData')));
        echo $this->Form->input('User.username', array('required'=>false, 'class'=>'username'));
        echo $this->Form->input('User.passwoed', array('required'=>false, 'class'=>'passwoed'));
        echo $this->Form->button('Save', array('id'=>'save'));
        echo $this->Form->end();
     </div> 
    ?> 

    Now let see view page ajax

    <script>
      $('#UserForm').submit(function(){
        $('.error').hide();
        var returnCheck = false;
        $.ajax({
          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).parent('div').find('.error').remove();
              $('.'+fieldName).after('<div class="error">'+message[0]+'</div>');
              });
            }else{
                returnCheck = true;
              }
          },
          error : function(jqXHR, textStatus, errorThrown){
             console.log(jqXHR+'-----'+textStatus+'-----'+errorThrown);
          }
        });
        return returnCheck;
      });
    
    </script>

    I hope this blog will be helpful to implement validation in your web application.

 0 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: