// async-validator rules
// to view at https://github.com/yiminghe/async-validator

const username = [
  {
    required: true,
    pattern: /^[a-zA-Z0-9_-]{2,19}$/,
    message: "用户名只能包含字母、数字、下划线以及短横线，长度3-20位",
    trigger: "change"
  }
];

const commonCode = ({ prop, min = 3, max = 20 }) => {
  return [
    {
      required: true,
      pattern: new RegExp(`^[a-zA-Z0-9_]{${min},${max}}$`),
      message: `${prop}只能由数字、字母和下划线组成，长度${min}-${max}个字符`,
      trigger: "change"
    }
  ];
};

const email = [
  {
    required: true,
    type: "email",
    message: "邮箱格式不正确",
    trigger: "change"
  }
];

const password = [
  {
    required: true,
    pattern: /^[a-zA-Z0-9_]{6,20}$/,
    message: "密码只能由数字、字母和下划线组成，长度6-20个字符",
    trigger: "change"
  }
];

const phone = [
  {
    required: true,
    pattern: /^1\d{10}$/,
    message: "请输入合适的手机号码",
    trigger: "change"
  }
];

const smscode = [
  {
    required: true,
    pattern: /^[a-zA-Z0-9]{4}$/,
    message: "请输入4位短信验证码",
    trigger: "change"
  }
];

const numberValidator = message => {
  return [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value && value !== 0) {
          callback(new Error(message));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ];
};

export {
  username,
  commonCode,
  email,
  password,
  phone,
  smscode,
  numberValidator
};
