gpt4 book ai didi

javascript - 客户端验证不发布值

转载 作者:行者123 更新时间:2023-11-28 06:54:23 25 4
gpt4 key购买 nike

我有一个可以一次验证一个值的表单。当所有值都经过验证并正确后,我的 ajax post 函数不想发布。我想在所有值都正确时发布。一个文本字段有一个名称,最后一个文本字段是电子邮件。

请检查我的jsFiddle以及下面的代码。

HTML:

<form enctype="multipart/form-data" method="post" id="myform" name="myform_1">
<input type="text" value="" id="name" name="myname" />
<input type="text" value="" id="email" name="myemail"/>
<input type="submit" value="Valid" id="validate" name="validate"/>
</form>

Javascript:

 $(document).ready(function(){
function checkLength( o, n, min, max ) {
if ( o.val().length > max || o.val().length < min )
{
o.css("background-color","#F30");
return false;
}
else
{
o.css("background-color","#FFF");
return true;
}
}

function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) )
{
o.css("background-color","#F30");
return false;
}
else
{
o.css("background-color","#FFF");
return true;
}
}

//Click action
$("#validate").click(function()
{
var name = $( "#name" );
var email = $("#email");
var valid = true;
emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/

valid = valid && checkLength( name,"Please enter a name",3,6);
valid = valid && checkRegexp( name, /^[a-z]([A-Z_\s])+$/i, "Name may consist of a-z, and 3 or more characters." );
valid = valid && checkLength( email, "email", 6, 80 );
valid = valid && checkkRegexp( email, emailRegex, "eg. ui@jquery.com" );
//Email
//alert ($("#myform").serialize());
//End of Email

if(valid)
{
var request = $.ajax({
url: "inc/newsletter.php", // Ofcourse this would be your addLike.php in your real script
type: "POST",
data: $("#myform").serialize()
});
request.done(function(msg) {
alert("Your details have been saved");
location.reload();
});

request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});

return valid;
}
else
{
alert("No;")
}
});
});

最佳答案

您的提交事件处理程序没有返回 false,因此它完全发布了表单。首先,确保事件冒泡在点击处理程序中停止通过以下方式:

$("#validate").click(function(event)
{
//YOUR AJAX CALL
//RETURN SHOULD ALWAYS BE FALSE FOR AJAX SUBMISSION WHEN CALLED FROM TYPE BUTTON
event.preventDefault();
event.stopPropagation();
return false;
})

然后您可以在浏览器控制台中跟踪 ajax 调用是否发生...

希望对你有帮助!

关于javascript - 客户端验证不发布值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32679453/

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