2

Currently I work with a registration form and wish to look up a php validation class implement in it for validation checking, I was found a class here provided by SchizoDuckie, my form will use ajax request to call a file reg_process.php, my problem is how can I use this class to validate required fields? and send to browser with errors message if found invalid input?

This is reg_process.php:

<?php
include('FormValidator.php');

$email = mysql_real_escape_string(strtolower(trim($_POST['email'])));
$password = mysql_real_escape_string(trim($_POST['password']));
$rpassword = mysql_real_escape_string(trim($_POST['rpassword']));
$fname = mysql_real_escape_string($_POST['fname']);
$contact = mysql_real_escape_string($_POST['contact']);

$validations = array(
    'name' => 'anything',
    'email' => 'email',
    'alias' => 'anything',
    'pwd'=>'anything',
    'gsm' => 'phone',
    'birthdate' => 'date');
$required = array('name', 'email', 'alias', 'pwd');
$sanatize = array('alias');

$validator = new FormValidator($validations, $required, $sanatize);

if($validator->validate($_POST))
{
    $_POST = $validator->sanatize($_POST);
    // now do your saving, $_POST has been sanatized.
    die($validator->getScript()."<script type='text/javascript'>alert('saved changes');    </script>");
}
else
{
    die($validator->getScript());
}
?>

ajax call:

$('#btn_reg').click(function(){
    var parameters = $('#reg_form').serialize();

    $.ajax({
        url: 'reg_process.php',
        type: 'POST',
        data: parameters,
        dataType: 'json',
        success: function(data){
            //how to get error if found invalid
        }
    });

});
Community
  • 1
  • 1
conmen
  • 2,377
  • 18
  • 68
  • 98

1 Answers1

0

A clean way to do it would be with HTTP Response Codes.

On success on the server side, respond with a 200 HTTP Response Code. Your jQuery ajax success callback will catch these responses and you can do what you wish with the data.

If validation fails, respond with a 500 error if something went wrong and catch it with the error callback.

Responding with the right response codes will help separate the good from the bad.

Also, it's probably not a good idea to pass back javascript directly because you'd have to eval() it.

gmartellino
  • 697
  • 5
  • 16