jQuery和Ajax表单验证

时间:2013-10-10 23:11:36

标签: javascript php jquery ajax forms

我遇到了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有什么意义呢。

如果有人可以帮助我,我将非常感激。

2 个答案:

答案 0 :(得分:1)

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

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

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

如果验证失败,您只需从submit()返回false即可避免提交表单。

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

答案 1 :(得分:0)

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

var validform = false;

并在表单提交事件中查看:

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

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

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

你也可以做一些自定义。

相关问题