Ant Design. How to set form field error message dynamically?

Viewed 50997

A form field has many asynchronous check rules, since a composited api can check these rules one time by return different result, i do not want to fire so many api request.

3 Answers

the syntax is updated in v4

new syntax is:

setFields.   |  Set fields status   |   (fields: FieldData[]) => void

example :

form.setFields([
   {
     name: 'field-to-update',
     errors: ['error-string'],
   },
]);

Use form.setFields

Syntax

Function({ fieldName: { value: any, errors: Error } })

Example from here -

this.props.form.setFields({
  user: {
    value: values.user,
    errors: [new Error('forbid ha')],
  },
});

When you need to add a custom error message just use validateStatus && help attributes. For example, you've got an error as loginError (string) in your props:

<Form.Item
    { ...props.loginError && {
        help: props.loginError,
        validateStatus: 'error',
    }}>
    {getFieldDecorator('email', {
        rules: [
            { required: true, message: 'You have to write the email' },
        ],
    })(
        <Input size="large"/>,
    )}
</Form.Item>
Related