CodeAgainst
CodeAgainst

Reputation: 153

Antd form.item required conditional

I have a form, with a password input, this form its used for Create a user, and for Edit that user, taking initialvalues from a state (internal), the code its like this:

<Form.Item
    label="Password"
    name="password"
    style={{ marginBottom: "14px" }}
    rules={[{
              pattern: new RegExp(/^((?=\S*?[A-Z])(?=\S*?[a-z])(?=\S*?[0-9]).{6,})\S$/),
              message: "uppercase, lowercase and number"},
            {required: true,
            message: "create a password",},]}
  >
    <Input.Password
      style={{ maxWidth: 300 }}
      autoComplete="off"
    />
  </Form.Item>

I need to disable the required password field when editing the user, that is when initialvalues are taking them out of the state, for example the field first_name: internal.first_name. so I tried this

required: ({ getFieldValue }) => getFieldValue("email") !== undefined ? true : false

But didn't work, always pass true. thanks for the "input"

Upvotes: 1

Views: 4778

Answers (1)

wakajawaka
wakajawaka

Reputation: 163

The variable to control the required attribute has to be reactive so keep track of it using useState().

const [isRequired, setIsRequired] = useState(true);
// Here if "edit mode" then setIsRequired(false);
<Form.Item rules={[{ required: isRequired }]}><Input /></Form.Item>

Upvotes: 2

Related Questions