实现通用的表单验证方法:
utils/validateItem.ts
// 应为正整数,且范围为1 ~ 99999
export function oneTo99999TestFlag(str) {
const reg = /^([1-9]{1}[0-9]{0,4})$/
return reg.test(str)
}
// 应为数字,且范围为1 ~ 99999(可小数)
export function oneTo99999DecimalTestFlag(str) {
const reg = /99999|(^[1-9]{1}[0-9]{0,3}[0-8]{0,1}(\.\d{1,2})?$)/
return reg.test(str)
}
// 应为数字,且范围为0 ~ 99999999.99且大于0
export function zeroTo99999999DecimalTestFlag(str) {
const reg = /(^[1-9](\d{0,7})(\.\d{1,2})?$)|(^0(\.\d{1,2})$)/
return reg.test(str)
}
// 请输入正确的联系邮箱
export function emailTestFlag(str) {
const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
return reg.test(str)
}
// 请输入正确的11位数联系电话
export function phoneTestFlag(str) {
const reg = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[\d]))\d{8}$/
return reg.test(str)
}
增加一个柯里化方法,用来生成表单验证函数:
utils/validate.ts
import * as Validates from './validateItem'
// 生成自定义校验函数
export const formValidate = (key, msg, isRequired?) => (rule, value, cb) => {
if (Validates[key](value)) {
cb()
} else {
if (isRequired == false && !value) {
cb()
} else {
cb(new Error(msg))
}
}
}
页面使用
非必填 传false
import { formValidate } from '@/utils/validate'
const abilityRules = ref<FormRules>({
phoneNumber: [
{
required: true,
message: '请输入联系电话',
trigger: 'blur',
},
{
validator: formValidate('phoneTestFlag', '请输入正确的11位数联系电话'),
trigger: ['blur', 'change'],
},
],
email: [
{
required: true,
message: '请输入联系邮箱',
trigger: 'blur',
},
{
validator: formValidate('emailTestFlag', '请输入正确的联系邮箱'),
trigger: ['blur', 'change'],
},
],
fixedAssets: [
{
validator: formValidate('oneTo99999DecimalTestFlag', '应为数值,且范围为1 ~ 99999', false),
trigger: ['blur', 'change'],
},
],
lastYearTotalSales: [
{
validator: formValidate('oneTo99999DecimalTestFlag', '应为数值,且范围为1 ~ 99999', false),
trigger: ['blur', 'change'],
},
],
employeeCount: [
{
validator: formValidate('oneTo99999TestFlag', '应为正整数,且范围为1 ~ 99999', false),
trigger: ['blur', 'change'],
},
],
})