Reputation: 444
I am trying to implement formik validation with Ant design form, formik is able to capture the input/selected data but when I click onSubmit, it doesn't print anything in console.
export default function SearchForm() {
const formik = useFormik({
initialValues: {
city: "",
checkIn: "",
},
onSubmit: (values) => {
console.log(values)
},
});
//console.log(formik.values)
return (
<Form onSubmit={formik.handleSubmit}>
<FormLabel>Select City</FormLabel>
<Form.Item>
<Select
name="city"
value={formik.values.city}
placeholder="Please select a country"
onChange={(value) => formik.setFieldValue("city", value)}
>
<Select.Option value="mumbai">Mumbai</Select.Option>
<Select.Option value="bengaluru">Bengaluru</Select.Option>
<Select.Option value="delhi">Delhi</Select.Option>
<Select.Option value="hyderabad">Hyderabad</Select.Option>
<Select.Option value="chennai">Chennai</Select.Option>
</Select>
</Form.Item>
<FormLabel>Check-In-Date</FormLabel>
<Form.Item>
<DatePicker
name="checkIn"
value={formik.values.checkIn}
format={dateFormat}
onChange={(value) => formik.setFieldValue("checkIn", value)}
/>
</Form.Item>
<SubmitButton htmlType="submit">Book Now</SubmitButton>
</Form>
);
}
And by giving values, the placeholder text is not visible, and also in DatePicker, it is saving as Moment Object.
Upvotes: 2
Views: 10616
Reputation: 444
finally, I got an answer!! When we use the Ant design form, it works a little different from the normal form, instead of using onSubmit
we have to use onFinish
and generally you pass value
and function to capture event.target.value
in normal form but in Ant design form we have to pass onChange={(value) => formik.setFieldValue("checkIn", value)}
and it will simply capture the change.
<Form onFinish={formik.handleSubmit}>
<FormLabel>Select City</FormLabel>
<Form.Item>
<Select
name="city"
placeholder="Please select a country"
onChange={(value) => formik.setFieldValue("city", value)}
>
<Select.Option value="mumbai">Mumbai</Select.Option>
<Select.Option value="bengaluru">Bengaluru</Select.Option>
<Select.Option value="delhi">Delhi</Select.Option>
<Select.Option value="hyderabad">Hyderabad</Select.Option>
<Select.Option value="chennai">Chennai</Select.Option>
</Select>
</Form.Item>
<FormLabel>Check-In-Date</FormLabel>
<Form.Item>
<DatePicker
name="checkIn"
format={dateFormat}
onChange={(value) => formik.setFieldValue("checkIn", value)}
/>
</Form.Item>
<SubmitButton htmlType="submit">Book Now</SubmitButton>
</Form>
Upvotes: 5
Reputation: 557
You can add Validation Schema
in useFormik
and import Yup
, like this :
import * as Yup from 'yup';
const FormSchema = Yup.object().shape({
title: Yup.string().required('Please enter notification title')
});
<Formik
validationSchema={FormSchema}>
<Form>
<div className='grid-row'>
<div className='grid-1'>
<Field name='title' required={true} label='Title'component={Input} />
</div>
</Form>
</Formik>
Upvotes: 2