Newer
Older
KaiFengPC / src / utils / validate-helper.js
@zhangdeliang zhangdeliang on 23 May 2 KB 初始化项目
export function required(fieldName = '', option = {}) {
  const defaultOpt = {
    required: true,
    message: `${fieldName}不能为空`,
    trigger: ['change', 'blur']
  }

  return {
    ...defaultOpt,
    ...option
  }
}

export function isInteger(fieldName = '', option = {}) {
  const IntegerRegex = /^\d+$/
  const defaultOpt = {
    trigger: ['change', 'blur'],
    validator: (rule, value, cb) => {
      if (value) {
        if (IntegerRegex.test(value)) {
          const max = option?.max
          const min = option?.min
          if (max && value * 1 > max) {
            cb(new Error(`${fieldName}不能大于${max}`))
          } else if((min || min === 0) && value * 1 < min) {
            cb(new Error(`${fieldName}不能小于${min}`))
          } else {
            cb()
          }
        } else {
          cb(new Error(`${fieldName}不正确`))
        }
      } else {
        option.required ? cb(new Error(`${fieldName}不能为空`)) : cb()
      }
    }
  }

  return {
    ...defaultOpt,
    ...option
  }
}

export const isNumber = (fieldName = '', option = {}) => {
  const numberRegex = /^(-?\d+)(\.\d+)?$/
  const defaultOpt = {
    trigger: ['change', 'blur'],
    validator: (rule, value, cb) => {
      if (value) {
        if (numberRegex.test(value)) {
          const max = option?.max
          const min = option?.min
          if (max && value * 1 > max) {
            cb(new Error(`${fieldName}不能大于${max}`))
          } else if((min || min === 0) && value * 1 < min) {
            cb(new Error(`${fieldName}不能小于${min}`))
          } else {
            cb()
          }
        } else {
          cb(new Error(`${fieldName}不正确`))
        }
      } else {
        option.required ? cb(new Error(`${fieldName}不能为空`)) : cb()
      }
    }
  }

  return {
    ...defaultOpt,
    ...option
  }
}

export const isScope = (fieldName = '', option = {}) => {
  const numberRegex = /^(-?\d+)(\.\d+)?$/
  const defaultOpt = {
    trigger: ['change', 'blur'],
    validator: (rule, value, cb) => {
      if (value) {
        if(numberRegex.test(value)){
          const data = option?.data?.value || option?.data || null
          if(!data) cb(new Error('校验异常'))
          const props = rule.field.split('.')
          const { downValue, upValue } = data[props[0]][props[1]]
          if(parseFloat(value) >= downValue * 1 && parseFloat(value) <= upValue * 1){
            cb()
          } else {
            cb(new Error('请输入参考值范围的值'))
          }
        } else {
          cb(new Error('请输入参考值范围的值'))
        }
      } else {
        option.required ? cb(new Error(`${fieldName}不能为空`)) : cb()
      }
    }
  }

  return {
    ...defaultOpt,
    ...option
  }
}