Savita.V.Malaghan
Savita.V.Malaghan

Reputation: 105

React js Validation for Range (Max and min values for field ) Using Formik

I'm trying to make a validation using React and Formik. I wanted to achieve that the max digit is only 3 and the max range should be only to 100 and minimum should be 1.

How can i achieve this in react js.

Upvotes: 1

Views: 4331

Answers (2)

Mohit Kushwaha
Mohit Kushwaha

Reputation: 1041

you can use validate prop of the Field component by passing a validation function to it.

import React from "react";
import ReactDOM from "react-dom";
import { Formik, Field, Form } from "formik";

function validate(value) {
  let error;
  if (value.length > 3) {
    error = "max digits 3";
  } else if (parseInt(value) > 100 || parseInt(value) < 1) {
    error = "range is 1 to 100";
  }
  return error;
}
const Basic = () => (
  <div>
    <Formik
      initialValues={{
        num: ""
      }}
      onSubmit={(values) => {
        // same shape as initial values
        console.log(values);
      }}
    >
      {({ errors, touched }) => (
        <Form>
          <Field type="number" name="num" validate={validate} />
          {errors.num && touched.num && (
            <div style={{ color: "red" }}>{errors.num}</div>
          )}
        </Form>
      )}
    </Formik>
  </div>
);

ReactDOM.render(<Basic />, document.getElementById("root"));

Upvotes: 2

Anurag Parmar
Anurag Parmar

Reputation: 293

There are many form schema validations libraries available out there one of the simpler one is Yup.

Take a look at this guide on how to use yup with formik

Upvotes: 1

Related Questions