簡體   English   中英

jQuery和Ajax表單驗證

[英]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;
    }
});

您也可以進行更多自定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM