如何通过验证提交可空输入值而不会收到错误消息?

时间:2018-01-18 23:57:33

标签: javascript jquery validation

当我尝试提交时,如果没有非必填字段,我会因验证而收到错误消息...那么如何在不禁用非必填字段的所有验证的情况下提交输入字段(地址,电话) )?

JQUERY

var contact_fs_name = $('#lb_firstname').val(); //required
var contact_ls_name = $('#lb_lastname').val(); //required
var contact_ur_name = $('#lb_email').val(); //required
var contact_pass = $('lb_password').val(); //required
var contact_address = $('#lb_address').val(); // can be null,empty
var contact_phone = $('#lb_phone').val(); // can be null,empty

if (contact_fs_name === "" || contact_ls_name === "" || contact_ur_name === "" || contact_pass === ""){
        alert("Please fill in all fields");

    } else if (!contact_address.match(/^(?=.*[a-z]).{3,20}$/)){

        alert("error_addr!");

    } else if (contact_phone.length < 10) {

        alert("error_phone!");

    }

1 个答案:

答案 0 :(得分:0)

以额外的条件包裹它们。检查空值或空值,如果不为空或&#39;&#39;检查验证。

见下文:

&#13;
&#13;
var contact_fs_name = $('#lb_firstname').val(); //required
var contact_ls_name = $('#lb_lastname').val(); //required
var contact_ur_name = $('#lb_email').val(); //required
var contact_pass = $('lb_password').val(); //required
var contact_address = $('#lb_address').val(); // can be null,empty
var contact_phone = $('#lb_phone').val(); // can be null,empty

if (contact_fs_name === "" || contact_ls_name === "" || contact_ur_name === "" || contact_pass === ""){
        alert("Please fill in all fields");
} else if (contact_address != '' && contact_address != null){
  if (!contact_address.match(/^(?=.*[a-z]).{3,20}$/)){
    alert("error_addr!");
  }
} else if(contact_phone != '' && contact_phone != null) {
    if (contact_phone.length < 10) {
      alert("error_phone!");
    }
}
&#13;
&#13;
&#13;