Skip to content

Instantly share code, notes, and snippets.

@shameerc
Created May 20, 2011 18:19
Show Gist options
  • Select an option

  • Save shameerc/983473 to your computer and use it in GitHub Desktop.

Select an option

Save shameerc/983473 to your computer and use it in GitHub Desktop.
Files used in ajax validation
<?php
/**
* @package Kohana validation
*
* @author shameer
*/
class Controller_User extends Controller_Default {
/**
* Validation function used for ajax validation
*/
public function action_validate()
{
//disable auto rendering if requested using ajax
if($this->request->is_ajax()){
$this->auto_render = FALSE;
}
if($this->request->post()){
$user = new Model_User();
// field name and the value to be validated
$array[$_POST['fieldName']] = $_POST['fieldVal'];
//check if there is any related fields
//if yes, add them to the array
if(!empty($_POST['related'])) {
foreach($_POST['related'] as $related){
$array[$related[0]] = $related[1];
}
}
//call the validation function
$validate = $user->validate($array);
//check if it satisfies all rules
if($validate->check()){
echo 'true';
}
else{
//if the validation fails, return the error message
echo json_encode($validate->errors('signup'));
}
}
}
}
?>
<?php
class Model_User extends Model {
/**
*
* Define the array of rules to be validated against
* the signup information
* @return array rules
*/
public function rules() {
return array(
'username' => array(array('not_empty'),
array('min_length', array(':value', 4)),
array('max_length', array(':value', 32)),
array('regex', array(':value', '/^[-\pL\pN_.]++$/uD')),
array(array($this, 'check_exists'), array(':validation', ':field')),
),
'password' => array(array('not_empty', NULL),
array('min_length', array(':value', 6)),
),
'passwordconfirm' => array(array('matches', array(':validation', 'passwordconfirm', 'password'))),
'email' => array(array('email', NULL),
array('not_empty', NULL),
array(array($this, 'check_exists'), array(':validation', ':field')),
)
);
}
/**
* Function to validate the input
*
* @param array $array Post data to be validated
* @return Validation object with rules applied
*/
public function validate($array) {
$post = Validation::factory($array);
$rules = $this->rules();
foreach ($array as $key => $val) {
$rules = $rules[$key];
$post->rules($key, $rules);
}
return $post;
}
/**
* Custom validation function to check if the value exists in the db
* in the given field. Used by the validation function
* @param Validation $array
* @param <type> $field
*/
public function check_exists(Validation $array, $field) {
$result = DB::select(array('count("*")', 'total_count'))
->from('users')
->where($field, '=', $array[$field])
->where('status', '!=', 'Deleted')
->execute($this->_db)
->get('total_count');
if ($result > 0) {
$array->error($field, 'check_exists', array($array[$field]));
}
}
}
?>
<?php defined('SYSPATH') or die('No direct script access.');
echo form::open('user/signup');
?>
<?php
if(!empty($errors)){
foreach($errors as $error){
echo $error.'<br>';
}
}
?>
<style type="text/css">
.error{
border-color:#CC3333;
}
</style>
<table>
<tr>
<td><?php echo Form::label('username', 'User Name'); ?></td>
<td><?php echo form::input('username',$post['username'],array('class'=>'validate','id'=>'username')); ?></td>
</tr>
<tr>
<td><?php echo Form::label('password', 'Password'); ?></td>
<td><?php echo form::password('password',$post['password'],array('class'=>'validate','id'=>'password')); ?></td>
</tr>
<tr>
<td><?php echo Form::label('passwordconfirm', 'Confirm Password'); ?></td>
<td><?php echo form::password('passwordconfirm',$post['passwordconfirm'],
array('class'=>'validate','rel'=>'password','id'=>'passwordconfirm')); ?></td>
</tr>
<tr>
<td><?php echo Form::label('email', 'Email'); ?></td>
<td><?php echo form::input('email',$post['email'],array('class'=>'validate','id'=>'email')); ?></td>
</tr>
<tr>
<td></td>
<td><?php echo form::submit('submit','Submit'); echo form::button('cancel', 'Cancel');?></td>
</tr>
</table>
<?php
echo form::close();
echo html::script('assets/js/validate.js');
?>
$(function(){
$('.validate').blur(function(){
var fieldName = $(this).attr('name');
var fieldVal = $.trim($(this).val());
$(this).removeClass('error');
if(typeof($(this).attr('rel'))!='undefined'){
var relFields = $(this).attr('rel').split('|');
var count = relFields.length;
var related = new Array();
for(i=0;i<count;i++){
$("#"+relFields[i]).removeClass('error');
sub =new Array();
sub.push(relFields[i]);
sub.push($.trim($("#"+relFields[i]).val()));
related.push(sub);
}
}
validate(fieldName,fieldVal,related);
})
$('.validate').focus(function(){
$(this).next('.formError').remove();
})
function validate(fieldName,fieldVal,related){
$.ajax({
type:'post',
url:'/kohana/index.php/ajax/validate',
data:({
fieldName:fieldName,
fieldVal:fieldVal,
related : related
}),
success:function(msg){
if(msg!=''){
var obj = $.parseJSON(msg);
var key='';
for(key in obj){
var errMessage ='<div class="reqformError formError" style="top: 142px; left: 724px; margin-top: 0px; opacity: 0.87;"><div class="formErrorContent">'+obj[key]+'<br></div></div>';
$('#'+key).after(errMessage);
$('#'+key).addClass('error');
}
}
}
})
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment