field-form icon indicating copy to clipboard operation
field-form copied to clipboard

什么时候删除自定义校验函数的包装器?

Open kaysonwu opened this issue 4 years ago • 1 comments

validateRules 函数会对自定义校验函数进行包装,这导致无法全面接收由 async-validator 传递过来的参数,比如 sourceoptions

全面接收参数的好处

  1. 验证出错时,通过响应 options.messages.[customRule] 消息即可消费 messageVariables
  2. 对于通过使用 ConfigProvider 做全局表单 validateMessages 提供了一致的地区语言方案
  3. 更简洁的代码

目前的解决方案

通过使用 asyncValidator 属性来避开包装器

import type { FormInstance, NamePath, RuleRender } from 'rc-field-form/lib/interface';

type ValidateMessages = import('rc-field-form/lib/interface').ValidateMessages & {
  confirmed: string;
};

type RuleObject = import('rc-field-form/lib/interface').RuleObject & {
  asyncValidator: (
    rule: RuleObject,
    value: import('rc-field-form/lib/interface').StoreValue,
    callback: (error?: string) => void,
    source: Record<string, import('rc-field-form/lib/interface').StoreValue>,
    options: import('rc-field-form/lib/interface').ValidateOptions & { messages: ValidateMessages }
  ) => void | Promise<void | string>;
}

export function confirmed(name: NamePath): RuleRender {
  return ({ getFieldValue }: FormInstance): RuleObject => ({
    asyncValidator: (rule, value, done, source, options) =>
      done(!value || getFieldValue(name) === value ? undefined : options.messages.confirmed),
  });
}

使用示例

自定义验证器示例

kaysonwu avatar Sep 10 '21 08:09 kaysonwu

@afc163 关于让自定义验证器也能消费 messageVariables 的建议,希望可以得到你的指点

kaysonwu avatar Sep 10 '21 08:09 kaysonwu