vue3单独封装表单校验函数

1.在页面中建一个.ts文件

import { useI18n } from '@/hooks/web/useI18n'
import { FormItemRule } from 'element-plus'

const { t } = useI18n()

interface LengthRange {
  min: number
  max: number
  message?: string
}
//必输项校验
export const useValidator = () => {
  const required = (message?: string): FormItemRule => {
    return {
      required: true,
      message: message || t('common.required')
    }
  }
//长度校验,字符转字节计算,英文字符按 1 字节计算,中文按两个字符
const customByteLengthRange = (options: LengthRange): FormItemRule => {
  const { min, max, message } = options

  return {
    validator: (_, val, callback) => {
      let length = 0
      for (let char of val) {
        if (/[\u4e00-\u9fa5]/.test(char)) {
          length += 2
        } else {
          length += 1
        }
      }

      if (length < min || length > max) {
        callback(new Error(message))
      } else {
        callback()
      }
    }
  }
}

//输入值不能包含空格
  const notSpace = (message?: string): FormItemRule => {
    return {
      validator: (_, val, callback) => {
        if (val?.indexOf(' ') !== -1) {
          callback(new Error(message || t('common.notSpace')))
        } else {
          callback()
        }
      }
    }
  }
//验证输入值不能包含特殊字符
  const notSpecialCharacters = (message?: string): FormItemRule => {
    return {
      validator: (_, val, callback) => {
        if (/[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/gi.test(val)) {
          callback(new Error(message || t('common.notSpecialCharacters')))
        } else {
          callback()
        }
      }
    }
  }

  return {
    required,
    customByteLengthRange ,
    notSpace,
    notSpecialCharacters
  }
}

2…vue组件内使用方法,useValidator()上面封装的.ts函数

const rules = {
  username: [
    useValidator().customByteLengthRange ({ min: 4, max: 20 }) // 汉字按 2 字节计算,英文字符按 1 字节计算
  ]
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值