gpt4 book ai didi

javascript - jQuery 和 Ajax 表单验证

转载 作者:行者123 更新时间:2023-11-30 05:43:41 25 4
gpt4 key购买 nike

我在使用 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 验证很容易被愚弄。

关于javascript - jQuery 和 Ajax 表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19307738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com