自定义验证器

创建同步/异步验证器,实现复杂的业务逻辑验证。

功能特性

  • ✅ 自定义同步验证器(密码强度)
  • ✅ 字段依赖验证(密码确认)
  • ✅ 异步验证器(检查用户名可用性)
  • ✅ 组合多个验证器
  • ✅ 实时验证反馈

创建自定义验证器

// 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'] // 关键!
    }
  }
});

交互演示

试试输入 admin、user、test 等已占用的用户名

💡 提示

  • 用户名会进行异步验证,模拟检查是否已被占用
  • 密码强度实时计算并显示
  • 确认密码依赖主密码字段,当主密码改变时自动重新验证
  • 尝试输入 "admin"、"user"、"test" 等用户名查看验证效果

表单状态

字段状态
{
  "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
  }
}