Search code examples
javascripttypescriptantdant-design-pro

Ant Design Form Custom Validator


In ant design one can provide a custom validator like the following:

<Form.Item label="First Name">
  {getFieldDecorator("firstName", {
    rules: [
      {
        validator: (rule: any, value: string, cb: (msg?: string) => void) => {
          value.length < 3 ? cb("too short") : cb();
        }
      }
    ]
  })(<Input />)}
</Form.Item>

As you see I'm using typescript and cause its transpiler is really cool it wants me to use rule parameter of validator as well. I can't find any documentation on it and don't know what is good for. So if you can please explain briefly what is it and how it should be used?


Solution

  • As part of Validation Rules validator accepts rules as first argument.

    Due to the fact it's a wrapper for async-validator, you can check the Rules specification:

    function(rule, value, callback, source, options)

    rule: The validation rule in the source descriptor that corresponds to the field name being validated. It is always assigned a field property with the name of the field being validated.

    You also can put a breakpoint and see its value for your needs.