correct-apricot
correct-apricot•3y ago

Form

<Input label="time" name="time" /> <Input label="timeUnit" name="timeUnit" /> How to require input timeUnit when entering value into input time?
10 Replies
kapa.ai
kapa.ai•3y ago
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:
const schema = Yup.object().shape({
time: Yup.string()
.required('This field is required'),
timeUnit: Yup.string().when(
"time",
(time: string, schema: Yup.StringSchema) => {
return time ? schema.required('This field is required') : schema
}
),
});
const schema = Yup.object().shape({
time: Yup.string()
.required('This field is required'),
timeUnit: Yup.string().when(
"time",
(time: string, schema: Yup.StringSchema) => {
return time ? schema.required('This field is required') : schema
}
),
});
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: ----------------------
kapa.ai
kapa.ai•3y ago
<@617879699363725341> kapa.ai is still learning and improving, please let us know how it did by reacting below
exotic-emerald
exotic-emerald•3y ago
Hello @hoaanhtuc
https://ant.design/components/input you can check ant design documentation
correct-apricot
correct-apricotOP•3y 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.
No description
exotic-emerald
exotic-emerald•3y ago
what is <SelectTimeUnit /> implementation ?
correct-apricot
correct-apricotOP•3y ago
I want when entering a value into time, timeUnit will be required, and vice versa
No description
correct-apricot
correct-apricotOP•3y ago
formProps?.form?.getFieldValue("time") is not working
exotic-emerald
exotic-emerald•3y 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 render
correct-apricot
correct-apricotOP•3y ago
const timeValues = Form.useWatch("time", formProps); great, it worked without state
exotic-emerald
exotic-emerald•3y ago
🚀 I'm glad to hear that

Did you find this page helpful?