gpt4 book ai didi

javascript - 在提交表单之前对输入标签执行验证

转载 作者:行者123 更新时间:2023-11-30 21:07:44 28 4
gpt4 key购买 nike

我有一个正在发布所有值的表单,但我需要对电话号码输入字段执行验证。我尝试使用 id 在输入标签上应用点击事件,但随后 HTML5 验证(必需)关闭

<form name="frm" method="post" id="callForm" >
<input type="tel" id="phone" name="phone" placeholder="(XXX) XXX-XXXX" required/>
<input id="submitbtn" value="Call Me!" type="submit" />
</form>

Js:

$('#submitbtn').click(function() {
if((frm.phone.value).length < 10)
{
alert("Phone number should be minimum 10 digits");
frm.phone.focus();
return false;
}

return true;
});

代码笔链接:https://codepen.io/rahulv/pen/rrwBdq

JavaScript:

$("input[type='tel']").each(function(){
$(this).on("change keyup paste", function (e) {
var output,
$this = $(this),
input = $this.val();

if(e.keyCode != 8) {
input = input.replace(/[^0-9]/g, '');
var area = input.substr(0, 3);
var pre = input.substr(3, 3);
var tel = input.substr(6, 4);
if (area.length < 3) {
output = "(" + area;
} else if (area.length == 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length == 3 && pre.length == 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}

$this.val(output);
}
});
});

最佳答案

使用这个

$('#submitbtn').click(function() {
if((frm.phone.value).length > 0)
{
if((frm.phone.value).length < 10)
{
alert("Phone number should be minimum 10 digits");
frm.phone.focus();
return false;
}

$( "#callForm" ).submit();
}

});

关于javascript - 在提交表单之前对输入标签执行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46450380/

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