deep-jade
deep-jade•10mo 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•10mo 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•10mo ago
<@617879699363725341> kapa.ai is still learning and improving, please let us know how it did by reacting below
ratty-blush
ratty-blush•10mo ago
Hello @hoaanhtuc
https://ant.design/components/input you can check ant design documentation
deep-jade
deep-jade•10mo 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
ratty-blush
ratty-blush•10mo ago
what is <SelectTimeUnit /> implementation ?
deep-jade
deep-jade•10mo ago
I want when entering a value into time, timeUnit will be required, and vice versa
No description
deep-jade
deep-jade•10mo ago
formProps?.form?.getFieldValue("time") is not working
ratty-blush
ratty-blush•10mo 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
deep-jade
deep-jade•10mo ago
const timeValues = Form.useWatch("time", formProps); great, it worked without state
ratty-blush
ratty-blush•10mo ago
🚀 I'm glad to hear that