简体   繁体   中英

jQuery and Ajax Form Validation

I have a problem with Jquery form validation.

I have this script:

$(document).ready(function () {
  var validateUsername = $('.info');
  $('#username').blur(function () {

var t = this; 
if (this.value != this.lastValue) {
  if (this.timer) clearTimeout(this.timer);
  validateUsername.removeClass();
  validateUsername.addClass('info');
  validateUsername.html('<img src="images/load.gif" height="16" width="16" /> checking availability...');

  this.timer = setTimeout(function () {
    $.ajax({
      async: false,
      cache: false,
      url: 'process.php',
      data: 'action=validateusername&username=' + t.value,
      dataType: 'json',
      type: 'post',
      success: function (j) {
        validateUsername.removeClass();
        validateUsername.addClass(j.class);
        validateUsername.html(j.msg); 
      }
    });

  }, 500);

  this.lastValue = this.value;
}

  })
});

and in php something like this :

public static function validateUserName($username) {
    $username = trim($username); // remove white spacing
    $response = array(); // define response array

    if(!$username) { // check if not empty
        $response = array(
            "ok"  => false,
            "class"  => "error",
            "msg" => "Please specify your username");
    } elseif (strlen($username)<5) { // check the lenght
        $response = array(
            "ok"  => false,
            "class"  => "error",
            "msg" => "UserName must be at least 5 characters long");
    } elseif (!preg_match('/^[a-zA-Z0-9.\-_]+$/',$username)) { // check the pattern
        $response = array(
            "ok"  => false,
            "class"  => "error",
            "msg" => "Your username can contain only Aplhanumerics, dash, underscore and period");
    } elseif (!self::userNameAvailable($username)) { // check availability
        $response = array(
            "ok"  => false,
            "class"  => "error",
            "msg" => "UserName already taken !");
    } else { // everything good
        $response = array(
            "ok"  => true,
            "class"  => "success",
            "msg" => "This username is free");
    }

    return $response;
}

As you can see php returns 3 fields of data.... problem is the user can still send the form even when php returns "false" and i have no idea how to fix it.

I could just let the form to be sent a do one more validating purely with php, but what is the point of using ajax then.

I´d be very thankful if somebody could help me.

Why do you validate every 500ms and not on form submit or input change?

General pattern for form validation using jQuery is to validate on form's submit() event, like:

$('form').submit(function () { 
    ...
    (validation code here)
    ...
});

If validation doesn't succeed, you can just return false from submit() to avoid submitting the form.

Also note that you need to do server-side validation of posted data, too , as jQuery validation can be fooled easily.

I think a simple solution is to set a global variable:

var validform = false;

And check it in form submit event :

$("#myform").submit(function(){
    return validform;
});

Now you can set it as TRUE or FALSE on your AJAX callback.

$.ajax({
  // Whatever',
    success: function (j) {
      validform = true;
    }
});

you can do a little more customization too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM