码迷,mamicode.com
首页 > Web开发 > 详细

js 创建简单的表单同步验证器

时间:2020-07-05 17:30:35      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:phone   value   export   date   大于   UNC   log   ret   one   

SyncValidate

/**
 * 同步验证器
 */
export class SyncValidate {

  /**
   * { [key]: Validate[] }
   * @param {Object} options
   */
  constructor(options) {
    this.options = options;
  }

  /**
   * check({key: value})
   * @param {Object} keyVal
   */
  check(keyVal) {
    const keys = Object.keys(keyVal);
    if (!keys.length) {
      throw new Error(‘至少的验证一个.‘)
    }

    // 只验证一个
    const key = keys[0];
    const val = keyVal[key];

    if (!this.options.hasOwnProperty(key)) {
      throw new Error(`没有设置[${key}]的验证器.`)
    }

    for (let v of this.options[key]) {
      const errorMessage = v(val);
      if (errorMessage) {
        if (this.validateErrorListener && typeof this.validateErrorListener === ‘function‘) {
          this.validateErrorListener(errorMessage)
        }
        // 验证失败立即返回
        return false;
      }
    }

    // 验证ok返回true
    return true;
  }

  // 添加验证错误时的回调函数
  addValidateErrorListener(validateErrorListener) {
    this.validateErrorListener = validateErrorListener;
  }


  // 必填
  static required(msg) {
    return (input) => {
      if (!input) return msg;
    }
  }

  // 最小长度
  static minLength(len, msg) {
    return (input) => {
      if (input.length < len) return msg;
    }
  }

  // 最大长度
  static maxLength(len, msg) {
    return (input) => {
      if (input.length > len) return msg;
    }
  }

  // 简单的验证手机号
  static phone(msg, exp) {
    const phoneExp = exp || /^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$/;
    return (input) => {
      if (!input.match(phoneExp)) {
        return msg;
      }
    }
  }
  
  // 简单的判断相等
  static eql(data, msg) {
    return (input) => {
      if(input !== data) return msg;
    }
  }
  
  // 简单的判断相等
  static equal(data, msg) {
    return (input) => {
      if(input != data) return msg;
    }
  }
}

使用

const syncValidate = new SyncValidate({
  username: [
    SyncValidate.required(‘用户名不能为空!‘),
    SyncValidate.phone(‘请输入正确手机号!‘),
  ],
  password: [
    SyncValidate.required(‘密码不能为空!‘),
    SyncValidate.minLength(8, ‘密码长度必须大于7‘),
  ]
});

syncValidate.addValidateErrorListener((errorMessage) => {
  uni.showToast({
    icon: ‘none‘,
    title: errorMessage,
    duration: 1500
  });
})

onLogin() {
if (
    !syncValidate.check({username: this.username.trim()})
    ||
    !syncValidate.check({password: this.password.trim()})
   ) 
      {
        return;
      }
        ...
}

js 创建简单的表单同步验证器

标签:phone   value   export   date   大于   UNC   log   ret   one   

原文地址:https://www.cnblogs.com/ajanuw/p/13246729.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!