index.js
<div className="form-group">
<label htmlFor='product_name'>Product Name:</label>
<input type="text" name="product_name" placeholder="Enter Product Name" className="form-control"
onChange={formik.handleChange} onBlur={formik.handleBlur} />
{
formik.touched.product_name && formik.errors.product_name && formik.values.product_name.length > 0 ? (
<div className='error'>{formik.errors.product_name}</div>) : null
}
</div>
I am using formik with react for validation but when I enter space it validates the form but I want if there is only space it does not validate until there is some text. Can anyone help me out
Use Yup.string().trim()
:
import * as Yup from "yup";
import React from "react";
import { Form, Formik } from "formik";
export default function App() {
return (
<Formik
initialValues={{ product_name: "" }}
onSubmit={(values) => console.log(values)}
validationSchema={Yup.object({
product_name: Yup.string().trim().required()
})}
>
{(formik) => (
<Form>
<div className="form-group">
<label htmlFor="product_name">Product Name:</label>
<input
type="text"
name="product_name"
placeholder="Enter Product Name"
className="form-control"
onChange={formik.handleChange}
onBlur={formik.handleBlur}
/>
{formik.touched.product_name && formik.errors.product_name ? (
<div className="error">{formik.errors.product_name}</div>
) : null}
</div>
</Form>
)}
</Formik>
);
}
https://codesandbox.io/s/wispy-smoke-ctzvz?file=/src/App.js:0-1050