vue前端校验合法IP地址和手机号码

第一种:用方法的形式写在外部,然后在校验规则中引用

    let validateIPAddress = (rule, value, callback) => {
      if (value == null) {
        return callback(new Error('IP地址不能为空'));
      }
      let regexp = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/;
      let valdata = value.split(',');
      let isCorrect = true;
      if (valdata.length) {
        for (let i = 0; i < valdata.length; i++) {
          if (regexp.test(valdata[i]) == false) {
            isCorrect = false;
          }
        }
      }
      if (!isCorrect) {
        callback(new Error('请输入正确的IP地址'));
      } else {
        callback()
      }
    }
// 表单校验
rules: {
  ipAddress: [{ required: true, validator: validateIPAddress, trigger: "blur" }]
}

第二种:直接放在表单校验规则里

// 表单校验
rules: {
  ipAddress: [{ required: true, pattern: /^(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9]))$/,message: "请输入正确的IP地址", trigger: "blur"}]
}
// ip校验规则
export function validateIPAddress(rule, value, callback){
				let regexp = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/;
				let valdata = value.split(',');
				let isCorrect = true;
					if (valdata.length) {
						for (let i = 0; i < valdata.length; i++) {
						   if (regexp.test(valdata[i]) == false) {
						       isCorrect = false;
						   }
						}
					}				      
					if (value == '') {
						return callback(new Error('请输入iP地址'));
					} else if (!isCorrect) {
						callback(new Error('请输入正确对ip地址'));
					} else {
						        callback()
					}
 }

validatorRules: {
           name: [
              { required: true, message: '请输入名称!'},
           ],
           ip: [
              { required: true, validator:validateIPAddress },
              //message: '请输入IP!',
           ],
}

export function validatePhone(rule, value, callback){
    let regexp = /^1[1356789]\d{9}$/.test(value)
    if (value == '') {
						return callback(new Error('请输入手机号码!'));
					} else if (!regexp) {
						callback(new Error('请输入正确手机号码!'));
					} else {
						        callback()
					}
  
  }

你可能感兴趣的:(前端,vue.js,tcp/ip)