Form
<Input label="time" name="time" />
<Input label="timeUnit" name="timeUnit" />
How to require input timeUnit when entering value into input time?10 Replies
Hi @hoaanhtuc. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
You can achieve this by using conditional validation with Yup, a JavaScript schema builder for value parsing and validation. In the validation schema, you can use the
when
method to add a condition to a field. The when
method allows you to change the validation schema of a field based on the value of another field.
Here's an example:
In this example, timeUnit
is required only if time
is filled. If time
is not filled, timeUnit
is not required.
You can find more information about this in the extracted source (https://discord.com/channels/837692625737613362/1158246064630009947).
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@617879699363725341> kapa.ai is still learning and improving, please let us know how it did by reacting below
helpful-purple•11mo ago
genetic-orange•11mo ago
<Form {...formProps}>
<Row gutter={24}>
<Col span={24}>
<InputForm label="time" name="time" />
</Col>
<Col span={24}>
<SelectTimeUnit
required={formProps?.form?.getFieldValue("time") ? true : false}
/>
</Col>
</Row>
</Form>
This is the form and log value I receive.
helpful-purple•11mo ago
what is <SelectTimeUnit /> implementation ?
genetic-orange•11mo ago
I want when entering a value into time, timeUnit will be required, and vice versa
genetic-orange•11mo ago
formProps?.form?.getFieldValue("time") is not working
helpful-purple•11mo ago
yes.
form?.getFieldValue("time")
comes from Antd design and does not sync with UI.
you can use https://ant.design/components/form#formusewatch or you can use react state to conditionaly rendergenetic-orange•11mo ago
const timeValues = Form.useWatch("time", formProps);
great, it worked without state
helpful-purple•11mo ago
🚀 I'm glad to hear that