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.
- 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.'
)
);
}
- Check validation in controller
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;
}
}
- View page html
<?php
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();
?>
- View page ajax
$('#UserDisplayForm').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;
});
0 Comment(s)