创建同步/异步验证器,实现复杂的业务逻辑验证。
// 1. 简单同步验证器
const strongPassword = createValidator((value: string) => {
if (!value) return null;
if (!/[A-Z]/.test(value)) return '必须包含大写字母';
if (!/[0-9]/.test(value)) return '必须包含数字';
return null;
});
// 2. 字段依赖验证器
const passwordMatch = createValidator(
(value, allValues) => {
if (value !== allValues.password) {
return '两次密码不一致';
}
return null;
}
);
// 3. 异步验证器
const usernameAvailable = createCustomValidator(
async (username) => {
const res = await fetch(`/api/check?user=${username}`);
return res.ok;
},
'该用户名已被占用'
);
// 使用
const form = useFormState({
fields: {
username: {
validator: Validators.compose(
Validators.required(),
usernameAvailable
)
},
confirmPassword: {
validator: passwordMatch,
dependencies: ['password'] // 关键!
}
}
});{
"username": {
"value": "",
"error": null,
"touched": false,
"dirty": false,
"validating": false
},
"password": {
"value": "",
"error": null,
"touched": false,
"dirty": false,
"validating": false
},
"confirmPassword": {
"value": "",
"error": null,
"touched": false,
"dirty": false,
"validating": false
}
}