I’m trying to validate post data using jquery and ajax for my registration form where an error message will be shown below each input fields. I manage to get the error message initially. But when some of the empty fields were updated with an input, the error message does not shown in the remaining empty field. Would somebody please be kind to point out if is there is any problem with below script?
<script type="text/javascript">
$(document).ready(function(){
$('#reg-form').submit(function(event){
// stop refreshing the page
event.preventDefault();
$('.reg_form').removeClass('has-error'); // remove the error class
$('.localError').remove(); // remove the error text
$('#response').html("<b>Processing your info..</b>");
var formMessages = $('#response');
var form = $('#reg-form');
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData,
dataType: 'JSON'
})
.done(function(data){
// log data to the console
console.log(data);
if (data !== '') {
// handle errors for username
if (data.username) {
$('#username-div').addClass('has-error'); // add the error class to show red input
$('#username-div').append('<div class="localError">' + data.username + '</div>'); // add the actual error message under our input
}
// handle errors for password ---------------
if (data.password) {
$('#password-div').addClass('has-error'); // add the error class to show red input
$('#password-div').append('<div class="localError">' + data.password + '</div>'); // add the actual error message under our input
}
// handle errors for conf_pass ---------------
if (data.conf_pass) {
$('#conf_pass-div').addClass('has-error'); // add the error class to show red input
$('#conf_pass-div').append('<div class="localError">' + data.conf_pass + '</div>'); // add the actual error message under our input
}
}
else {
//Turn the response alert into a success alert
$('#response').addClass('alert-success');
$('#response').removeClass('alert-error');
//Add the success message text into the alert
$('#response').html("<i class='success'></i> Form validated successfully!").fadeIn();
}
})
.fail(function() {
// just in case posting your form failed
alert( "Error.." );
});
return false;
});
});
</script>
regsiter.php
<div id="reg">
<!-- where the response will be displayed -->
<div id='response'></div>
<form action="register-handler.php" method="POST" id="reg-form">
<div id='username-div' class='reg_form'>
<label for="username" >Username:</label></br>
<input type="text" name="username" id="username" autocomplete="off">
</div>
<div id='password-div' class='reg_form'>
<label for="password" >Password:</label></br>
<input type="password" name="password" id="password" >
</div>
<div id='conf_pass-div' class='reg_form'>
<label for="conf_pass" >Confirm Password:<label></br>
<input type="password" name="conf_pass" id="conf_pass" >
</div>
<div></div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input type="submit" value="submit"></td>
</form>
</div>
register-handler.php
<?php
require_once 'core/init.php';
if(Input::exists()){
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true,
'min' => 2,
'max' => 20,
'unique' => 'users'
),
'password' => array(
'required' => true,
'min' => 6
),
'conf_pass' => array(
'required' => true,
'matches' => 'password'
)
));
if($validation->passed()) {
//register user
$user = new User();
$salt = Hash::salt(32);
try {
$user->create(array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password'), $salt),
'salt' => $salt
));
Session::flash('home', 'You have been registered and can now log in!');
Redirect::to('index.php');
} catch(Exception $e) {
die($e->getMessage());
}
}
else {
//output errors
header('Content-Type: application/json');
echo json_encode($validation->errors());
}
}
}
}
?>
validate.php
<?php
class Validate {
private $_passed = false,
$_errors = array()
public function check($source, $items = array()) {
foreach ($items as $item => $rules) {
foreach ($rules as $rule => $rule_value) {
$value = trim($source[$item]);
$item = escape($item);
if ($rule === 'required' && empty($value)) {
$this->addError($item, "{$item} is empty");
} else if (!empty($value)) {
switch ($rule) {
case 'min':
if (strlen($value) < $rule_value) {
$this->addError($item, "{$item} must be a minimum of {$rule_value} characters.");
}
break;
case 'max':
if (strlen($value) > $rule_value) {
$this->addError($item, "{$item} must be a maximum of {$rule_value} characters.");
}
break;
case 'matches':
if ($value != $source[$rule_value]) {
$this->addError($item, "{$rule_value} must match {$item}");
}
break;
}
}
}
}
if (empty($this->_errors)) {
$this->_passed = true;
}
return $this;
}
private function addError($key, $error) {
$this->_errors[$key] = $error;
}
public function errors() {
return $this->_errors;
}
public function passed() {
return $this->_passed;
}
}
?>