gpt4 book ai didi

javascript - 当字段值无效时表单提交

转载 作者:行者123 更新时间:2023-11-28 05:29:21 25 4
gpt4 key购买 nike

我编写了一个带有单个输入的表单,该表单获取用户的手机号码并以 0 开头进行验证。验证效果很好,但问题是当我提交表单时,它不会检查我的输入框的值并提交我的表单,即使字段无效。我想检查我的字段的验证,当它有效时就可以提交。

这是我的代码:

$('#mobili').focusout(function() {
$('#mobili').filter(function() {
var mobi = $('#mobili').val();
var mobiback = $('#mobili');
var mobilReg = /^([0][0-9]{10})$/;
if (!mobilReg.test(mobi)) {
$("#error-nwl").css('color', '#ff6666');
$("#error-nwl").text("Enter valid mobile number (begin with 0)");
} else {
$("#error-nwl").css('color', '#66cc66');
$("#error-nwl").text("ok");
}
})
});

$(".newslside").submit(function(e) {
var url = "page2.html";
alert("Submitted");
$.ajax({
type: "POST",
url: url,
data: $(".newslside").serialize(),
success: function(data) {
$(".errori").html(data),
alert("Submitted");
}
});
e.preventDefault();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="error-nwl"></div>
<form action="" method="post" name="myForm" class="newslside">
<input type="text" placeholder="Mobile" name="mobile" id="mobili" maxlength="11" required />
<br/>
<button class="submitnews" type="submit">send</button>
</form>

谢谢

最佳答案

希望这会起作用,

$('#mobili').focusout(function() {
$('#mobili').filter(function() {
var mobi = $('#mobili').val();
var mobiback = $('#mobili');
var mobilReg = /^([0][0-9]{10})$/;
if (!mobilReg.test(mobi)) {
$("#error-nwl").css('color', '#ff6666');
$("#error-nwl").text("Enter valid mobile number (begin with 0)");
} else {
$("#error-nwl").css('color', '#66cc66');
$("#error-nwl").text("ok");
}
})
});

$(".newslside").submit(function(e) {

var mobi = $('#mobili').val();
var mobiback = $('#mobili');
var mobilReg = /^([0][0-9]{10})$/;
if (!mobilReg.test(mobi)) {
$("#error-nwl").css('color', '#ff6666');
$("#error-nwl").text("Enter valid mobile number (begin with 0)");
return false;
}else{
var url = "page2.html";
alert("Submitted");
$.ajax({
type: "POST",
url: url,
data: $(".newslside").serialize(),
success: function(data) {
$(".errori").html(data),
alert("Submitted");
}
});
}
e.preventDefault();
});

关于javascript - 当字段值无效时表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39848078/

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