欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用jquery.validate自定义方法教程实现手机号码或者固话至少填写一个的逻辑验证

程序员文章站 2022-06-05 21:11:36
最近项目开发中遇到这样的需求“手机号码或者固话至少填写一个”,项目采用的jquery.validate.js验证,目前组件不支持这种“或&rdq...

最近项目开发中遇到这样的需求“手机号码或者固话至少填写一个”,项目采用的jquery.validate.js验证,目前组件不支持这种“或”逻辑的验证,于是就自己定义一个

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");

补充isempty函数:

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

处理validate的errorplacement:

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


在rules里面使用

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