DEV Community

Cover image for form validation using react js
Muhammed Shamal PV
Muhammed Shamal PV

Posted on • Edited on

form validation using react js

Follow me on LinkedIn
Follow me on Github.com

Click & Read

0.Form Validation Without Third-Party Libraries

import React, { useState } from 'react';

function BasicFormValidation() {
  const [formData, setFormData] = useState({ name: '', email: '' });
  const [errors, setErrors] = useState({});

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };

  const validate = () => {
    let tempErrors = {};
    tempErrors.name = formData.name ? "" : "Name is required";
    tempErrors.email = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(formData.email) ? "" : "Email is not valid";
    setErrors(tempErrors);
    return Object.keys(tempErrors).every(x => tempErrors[x] === "");
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (validate()) {
      alert("Form submitted successfully");
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Name</label>
        <input type="text" name="name" value={formData.name} onChange={handleChange} />
        {errors.name && <div style={{ color: 'red' }}>{errors.name}</div>}
      </div>
      <div>
        <label>Email</label>
        <input type="email" name="email" value={formData.email} onChange={handleChange} />
        {errors.email && <div style={{ color: 'red' }}>{errors.email}</div>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default BasicFormValidation;

Enter fullscreen mode Exit fullscreen mode

1.Using React Hooks

import React, { useState, useEffect } from 'react';

function HookFormValidation() {
  const [formData, setFormData] = useState({ username: '', password: '' });
  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };

  const validate = () => {
    let tempErrors = {};
    tempErrors.username = formData.username ? "" : "Username is required";
    tempErrors.password = formData.password.length > 6 ? "" : "Password must be at least 6 characters long";
    setErrors(tempErrors);
    return Object.keys(tempErrors).every(x => tempErrors[x] === "");
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (validate()) {
      setIsSubmitting(true);
    }
  };

  useEffect(() => {
    if (isSubmitting) {
      alert("Form submitted successfully");
      setIsSubmitting(false);
    }
  }, [isSubmitting]);

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Username</label>
        <input type="text" name="username" value={formData.username} onChange={handleChange} />
        {errors.username && <div style={{ color: 'red' }}>{errors.username}</div>}
      </div>
      <div>
        <label>Password</label>
        <input type="password" name="password" value={formData.password} onChange={handleChange} />
        {errors.password && <div style={{ color: 'red' }}>{errors.password}</div>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default HookFormValidation;

Enter fullscreen mode Exit fullscreen mode

2.Form Validation With Third-Party Libraries

import React from 'react';
import { useFormik } from 'formik';
import * as Yup from 'yup';

const FormikFormValidation = () => {
  const formik = useFormik({
    initialValues: {
      firstName: '',
      lastName: '',
      email: '',
    },
    validationSchema: Yup.object({
      firstName: Yup.string()
        .max(15, 'Must be 15 characters or less')
        .required('Required'),
      lastName: Yup.string()
        .max(20, 'Must be 20 characters or less')
        .required('Required'),
      email: Yup.string().email('Invalid email address').required('Required'),
    }),
    onSubmit: (values) => {
      alert(JSON.stringify(values, null, 2));
    },
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <div>
        <label>First Name</label>
        <input
          type="text"
          name="firstName"
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          value={formik.values.firstName}
        />
        {formik.touched.firstName && formik.errors.firstName ? (
          <div style={{ color: 'red' }}>{formik.errors.firstName}</div>
        ) : null}
      </div>
      <div>
        <label>Last Name</label>
        <input
          type="text"
          name="lastName"
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          value={formik.values.lastName}
        />
        {formik.touched.lastName && formik.errors.lastName ? (
          <div style={{ color: 'red' }}>{formik.errors.lastName}</div>
        ) : null}
      </div>
      <div>
        <label>Email</label>
        <input
          type="email"
          name="email"
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          value={formik.values.email}
        />
        {formik.touched.email && formik.errors.email ? (
          <div style={{ color: 'red' }}>{formik.errors.email}</div>
        ) : null}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default FormikFormValidation;

Enter fullscreen mode Exit fullscreen mode

3.Using React Hook Form

import React from 'react';
import { useForm } from 'react-hook-form';

function ReactHookFormValidation() {
  const { register, handleSubmit, watch, formState: { errors } } = useForm();
  const onSubmit = (data) => alert(JSON.stringify(data));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label>Username</label>
        <input {...register("username", { required: "Username is required" })} />
        {errors.username && <div style={{ color: 'red' }}>{errors.username.message}</div>}
      </div>
      <div>
        <label>Password</label>
        <input {...register("password", { required: "Password is required", minLength: { value: 6, message: "Password must be at least 6 characters long" } })} />
        {errors.password && <div style={{ color: 'red' }}>{errors.password.message}</div>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default ReactHookFormValidation;

Enter fullscreen mode Exit fullscreen mode

4.Using Yup with Formik

import React from 'react';
import { useFormik } from 'formik';
import * as Yup from 'yup';

const FormikYupValidation = () => {
  const formik = useFormik({
    initialValues: {
      username: '',
      email: '',
    },
    validationSchema: Yup.object({
      username: Yup.string()
        .max(15, 'Must be 15 characters or less')
        .required('Required'),
      email: Yup.string().email('Invalid email address').required('Required'),
    }),
    onSubmit: (values) => {
      alert(JSON.stringify(values, null, 2));
    },
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <div>
        <label>Username</label>
        <input
          type="text"
          name="username"
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          value={formik.values.username}
        />
        {formik.touched.username && formik.errors.username ? (
          <div style={{ color: 'red' }}>{formik.errors.username}</div>
        ) : null}
      </div>
      <div>
        <label>Email</label>
        <input
          type="email"
          name="email"
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          value={formik.values.email}
        />
        {formik.touched.email && formik.errors.email ? (
          <div style={{ color: 'red' }}>{formik.errors.email}</div>
        ) : null}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default FormikYupValidation;

Enter fullscreen mode Exit fullscreen mode

Byyyy
Happy Coding !

Top comments (0)