在提交表单之前对输入标记执行验证

时间:2017-09-27 14:22:40

标签: javascript jquery html5 forms validation

我的表格是POSTING所有值,但我需要在电话号码输入字段上执行验证。 我尝试使用id在输入标记上应用click事件,然后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);
}
});
});

2 个答案:

答案 0 :(得分:1)

使用此

$('#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();
    }

});

答案 1 :(得分:0)

禁用表单上的html5验证

<form name="frm" method="post" id="callForm" novalidate>

添加'novalidate'属性。