vue3单独封装表单校验函数
1.在页面中建一个.ts文件
import { useI18n } from '@/hooks/web/useI18n'
import { FormItemRule } from 'element-plus'const { t } = useI18n()interface LengthRange {min: numbermax: numbermessage?: 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 } = optionsreturn {validator: (_, val, callback) => {let length = 0for (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 字节计算]
}