Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Space validation in react using react formik

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

like image 735
Shubham Sharma Avatar asked Mar 05 '26 03:03

Shubham Sharma


2 Answers

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

like image 165
Ciarán Tobin Avatar answered Mar 07 '26 16:03

Ciarán Tobin


You can try this:

  {
    formik.touched.product_name && formik.errors.product_name && formik.values.product_name.trim().length > 0 && formik.values.product_name.length > 0 ? (
      <div className='error'>{formik.errors.product_name}</div>) : null
  }

Where this ought to solve your issue: formik.values.product_name.trim().length > 0

like image 33
Lazar Nikolic Avatar answered Mar 07 '26 17:03

Lazar Nikolic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!