jQuery and Ajax Form Validation


jQuery and Ajax Form Validation

我在Jquery表单验证方面遇到问题。

我有这个脚本:

$(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;
}
  })
});

在 PHP 中是这样的:

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;
}

如您所见,php 返回 3 个数据字段。问题是即使 PHP 返回"false",用户仍然可以发送表单,我不知道如何解决它。

我可以让要发送的表单再做一个纯粹用 php 验证,但是使用Ajax有什么意义呢?

如果有人能帮助我,我将不胜感激。

为什么每 500 毫秒验证一次,而不是在表单提交或输入更改时验证一次?

使用 jQuery 进行表单验证的一般模式是对表单的submit()事件进行验证,例如:

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

如果验证不成功,您可以只从submit()返回 false 以避免提交表单。

另请注意,您还需要对发布的数据进行服务器端验证,因为jQuery验证很容易被愚弄。

我认为一个简单的解决方案是设置一个全局变量:

var validform = false;

并在表单提交事件中检查它:

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

现在,您可以在 AJAX 回调中将其设置为 TRUE 或 FALSE。

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

您也可以进行更多的自定义。