1
votes

Could you please tell me how to make a field required dynamically?

I have two fields firstName and lastName. First name is required. I want lastName to become a required field if I type test in firstName.

Is it possible?

Here is my code https://codesandbox.io/s/unruffled-pike-5k7jn

 <Field
            name="lastName"
            validate={values.firstName === "test" ? required : ""}
          >
            {({ input, meta }) => (
              <div>
                <label>Last Name</label>
                <input {...input} type="text" placeholder="Last Name" />
                {meta.error && meta.touched && <span>{meta.error}</span>}
              </div>
            )}
          </Field>

Can I make the second field required only if user types test in first name field?

API link

https://final-form.org/docs/react-final-form/examples

To see it not working reproduce these steps:

1) click submit button. It shows firstname is required.

2) enter test text in first name field.

3) press submit button again.

It is not showing required error. Why?

2
You have a syntax error on line 5 of index.js in codesandbox.io/s/unruffled-pike-5k7jn - Sharon

2 Answers

3
votes

instead of putting field-level validation you can put validation in the Form tag

   <Form
      onSubmit={onSubmit}
      validate={values => {
        const errors = {};
        if (!values.firstName) {
          errors.firstName = "Required";
        }
        if (!values.lastName && values.firstName === "test") {
          errors.lastName = "Required";
        }
        return errors;
      }}

here is the link of modified version of your codesandbox

1
votes

This is because your

<Field name = "lastName/>

props does not update in real time. You can try console.log(values.firstName) inside the validate function to confirm this. To get around this my way is quite a hack, just add key = {values.firstName} to Field component like this

<Field key = {values.firstName} name = "lastName" validate = {values.firstName === "test" ? required : ""}> 
...renderStuffs
</Field>