'Ant Design Conditionally Require Form.Item

How to conditionally require a Form.Item in Ant design?

rules={[
   {
       required: {this.state.isRequired},
       message: 'This field is required',
   },
]}

Doesn't work with a variable as the value

I can use

<Form.Item>
 required={this.state.isRequired}
</Form.Item>

To get the star to show up, indicating it is required, but doesn't actually prevent a user from submitting without a value



Solution 1:[1]

Remove curly braces from required: {this.state.isRequired}

You can also use ternary operator in order to apply conditional required.

example:

let condition = true

rules={[
   {
       condition ? this.state.isRequired: null,
       message: 'This field is required',
   },
]}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rahul Sarma