js表单验证(1):域名校验指令

angularjs实现

app.directive('checkDomainCommon', function () {
  return {
    restrict: 'A',
    require: 'ngModel',
    link(scope, ele, attrs, ctrl) {

      ctrl.$validators.checkDomainCommon = function (modelVal) {
        // reg为域名的正则的正则
        let reg =/^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][--a-zA-Z0-9]{0,62})+\.?/
        if (attrs['required'] === undefined || attrs['required'] === false) {
          return true
        }
        else if(!modelVal){
          return false;
        }else {
          //加入输入类型判断,防止错误的将指令绑定在如number类型的输入框上
          if(typeof modelVal !== 'string'){
            console.error('the type of input value is not string,can not check domain format!');
            return false;
          }
          // 系统中现有用逗号分隔的,和分号分隔的做兼容。都是英文符号
          // 中横线隔开的是domain范围,也需要验证是否符合输入规范
          let domainArr = attrs['separatorReg']? modelVal.split(new RegExp(attrs['separatorReg'])):modelVal.split(/,|;|-/);
          let domain = "";
          let isOk = false;
          for (let i = 0; i < domainArr.length; i++) {
            domain = domainArr[i];
            if (reg.test(domain)) {
              isOk = true;
            } else {
              // 只要一个不合符,未通过验证,直接break
              isOk = false;
              break;
            }
          }

          return isOk;
        }
      }
    }
  }
});

vue实现

import Vue from 'vue'

const domianReg = '';

// 注册一个全局自定义指令 `v-checkDomain`
Vue.directive('checkDomain', {
    // 当被绑定的元素插入到 DOM 中时……
    inserted: function (el, binding, vNode) {
        el.addEventListener('keyup', function (event) {
            // 首先去除已有样式

            //removeErrorStyle
            
            // 判断是否是否必填
            let isRequired = binding.value.required
            if (isRequired) {
                if (!el.value || el.value === '') {
                    //do something with error 
                }
            }

            // 判断正则
            let regex = binding.value.regex
            if (regex === 'IpRegex') {
                if (!el.value.match(domainReg)) {
                    //do something with error 
                }
            } else if (!el.value.match(regex)) {
                //do something with error 
            }
        })
    }
})

// 注册一个全局自定义指令 `v-checkSubmit`
Vue.directive('checkSubmit', {
    // 当被绑定的元素插入到 DOM 中时……
    inserted: function (el, binding, vNode) {
        el.addEventListener('click', function (event) {
            let elements = document.getElementsByClassName('v-check')
            var evObj = document.createEvent('Event')
            evObj.initEvent('keyup', true, true)
            for (let element of elements) {
                element.dispatchEvent(evObj)
            }
            let errorInputs = document.getElementsByClassName('errorClssDom');
            if (errorInputs.length === 0) {
                vNode.context.submit();
            }
        })
    }
})

你可能感兴趣的:(javascript,vue.js,angularjs)