1、定义一个表单验证规则对象
const validateRules = {
// 非空验证
required: {
message: '此项为必填项',
validate: (value) => !!value,
},
// 最大长度验证
max: (max) => ({
message: `输入内容长度不能超过${max}个字符`,
validate: (value) => (!value || value.length <= max),
}),
// 最小长度验证
min: (min) => ({
message: `输入内容长度不能少于${min}个字符`,
validate: (value) => (!value || value.length >= min),
}),
// 数值范围验证
range: (min, max) => ({
message: `输入值必须在${min}和${max}之间`,
validate: (value) => (!value || (Number(value) >= min && Number(value) <= max)),
}),
// 正则表达式验证
pattern: (pattern) => ({
message: '输入格式不正确',
validate: (value) => (!value || pattern.test(value)),
}),
// 验证两次输入是否一致
equalTo: (target) => ({
message: '两次输入不一致',
validate: (value) => (value === target.value),
}),
};
2、使用示例
const useValidate = () => {
// 应用验证规则
const validate = (rules, data) => {
const errors = {};
Object.keys(rules).forEach((key) => {
const rule = rules[key];
const validator = Array.isArray(rule) ? rule : [rule];
validator.forEach((r) => {
if (typeof r === 'function') {
const result = r(data[key]);
if (!result.validate) {
errors[key] = result.message;
}
} else if (typeof r === 'object' && r.validate && !r.validate(data[key])) {
errors[key] = r.message;
}
});
});
return errors;
};
return {
validate,
validateRules,
};
};
3、使用
// 使用
const { validate, validateRules } = useValidate();
// 定义表单规则
const formRules = {
username: [validateRules.required, validateRules.max(10)],
age: [validateRules.required, validateRules.range(18, 60)],
};
// 表单数据
const formData = {
username: 'Alice',
age: '25',
};
// 执行验证
const errors = validate(formRules, formData);
console.log(errors);