Home >Web Front-end >JS Tutorial >Use the jquery.validate custom method to implement the logical verification of 'fill in at least one mobile number or landline number'_jquery

Use the jquery.validate custom method to implement the logical verification of 'fill in at least one mobile number or landline number'_jquery

WBOY
WBOYOriginal
2016-05-16 16:38:121355browse

In recent project development, we have encountered the requirement of "fill in at least one mobile phone number or landline number", as shown in the figure below:

The jquery.validate.js verification component used in the project currently does not support this kind of "or" logic verification, so I defined one myself

jQuery.validator.addMethod("phone", function(value, element) {
      var mobile = $("#mobile").val();// 手机号码
      var telephone = $("#telephone").val();// 固定电话
      var mobileRule = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0-9]|170)\d{8}$/;
      var telephoneRule = /^\d{3,4}-?\d{7,9}$/;

      // 都没填
      if (isEmpty(mobile) && isEmpty(telephone)) {
        //自定义错误提示
        $("#receivingMobile_tip").addClass("errorHint").text("请填写固定电话或手机号码");
        return false;
      }
      var mobilePass = false;
      var telephonePass = false;
      // 手机填了、固定电话没填
      if (!isEmpty(mobile) && isEmpty(telephone)) {
        if (!mobileRule.test(mobile)) {
          //自定义错误提示
          $("#receivingMobilePhone_tip").removeClass("successHint").addClass("errorHint").text("手机号码格式不对");
          return false;
        } else {
          mobilePass = true;
        }
      }

      // 手机没填、固定电话填了
      if (isEmpty(mobile) && !isEmpty(telephone)) {
        if (!telephoneRule.test(telephone)) {
          //自定义错误提示
          $("#receivingTelephone_tip").removeClass("successHint").addClass("errorHint").text("固定电话格式不对");
          return false;
        } else {
          telephonePass = true;
        }
      }

      if (mobilePass || telephonePass) {
        //自定义成功提示
        $("#receivingTelephone_tip").removeClass("errorHint").addClass("successHint").text('');
        return true;
      } else {
        return false;
      }
    }, "ignore");

Supplement isEmpty function:

 // 空字符串判断
function isEmpty(v, allowBlank) {
   return v === null || v === undefined || (!allowBlank ? v === "" : false);
}

Handling errorPlacement of validate:

errorPlacement : function(error, element) {
        //忽略自定义的方法错误提示
        if (error.text() == "ignore") {
          return;
        }
         
      }


Use

in rules
rules : {
        telephone : {
          phone : []
        },
        mobile : {
          phone : []
        }
      }

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn