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 bee a required field if I type test
in firstName.
Is it possible?
Here is my code
<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
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?
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 bee 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/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?
Share Improve this question edited Aug 12, 2019 at 13:52 Sharon 13816 bronze badges asked Aug 12, 2019 at 11:36 user944513user944513 12.8k52 gold badges185 silver badges348 bronze badges 1- You have a syntax error on line 5 of index.js in codesandbox.io/s/unruffled-pike-5k7jn – Sharon Commented Aug 12, 2019 at 13:09
2 Answers
Reset to default 3instead 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
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 ponent like this
<Field key = {values.firstName} name = "lastName" validate = {values.firstName === "test" ? required : ""}>
...renderStuffs
</Field>