我对 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 有什么意义。
如果有人可以帮助我,我将非常感激。