How to Validate input fields in ReactJS

Validate input data, email, and password into reactJS. To build or create user authentication functionalities or booking any schedules or adding any date’s validation is a must. Without proper validation, things might not work perfectly as they should.

In this article, we will show how to,

  • Validate date.
  • Validate a strong password.
  • Validate the email. 

Validate Date in ReactJS

  • Open up a React project
  • Create an input field in App.js component
function App() {
  return (
    <div className="min-h-screen flex justify-center items-center">
      <input type="text" placeholder="MM-DD-YYYY" class="input input-bordered w-full max-w-xs bg-white text-black" />
    </div>
  );
}

export default App;

1

Note: we are using tailwindCSS style classes. To know more about it, Read this article.

  • Declare a state using useState() hook of ReactJS.
import { useState } from "react";

function App() {
// declaring the state hook
  const [date, setDate] = useState('')
  return (
    <div className="min-h-screen flex justify-center items-center">
      <input type="text" placeholder="MM-DD-YYYY" class="input input-bordered w-full max-w-xs bg-white text-black" />
    </div>
  );
}

export default App;
  • Add an onChange()  event in the input field
import { useState } from "react";

function App() {
  // declaring the state hook
  const [date, setDate] = useState('')
  return (
    <div className="min-h-screen flex justify-center items-center">
      <input type="text" placeholder="MM-DD-YYYY" class="input input-bordered w-full max-w-xs bg-white text-black" onChange={(e) => setDate(e.target.value)} />
    </div>
  );
}

export default App;

This state hook will hold all the values that will be input into the input field.

  • Install momentjs to validate date by running npm install moment --save in command prompt.

  • After finish installing, import “moment” in the App.js component.
import moment from "moment";
  • Write the below code in the component
import moment from "moment";
import React, { useState } from "react";

const App= () => {
    const [date, setDate] = useState('')
    const dateFormat = 'MM-DD-YYYY';
    const toDateFormat = moment(new Date(date)).format(dateFormat);


    const validateDate = moment(toDateFormat, dateFormat, true).isValid();
    return (
        <div className="min-h-screen flex justify-center items-center">
            <input type="text" placeholder="MM-DD-YYYY" class="input input-bordered w-full max-w-xs bg-white text-black" onChange={(e) => setDate(e.target.value)} />
            <div>
                {
                    validateDate ? <p className="text-green-300">Correct format</p> : <p className="text-red-500">Wrong format</p>
                }
            </div>
        </div>
    );
}

export default App

Here, we are using React’s Date() method and date format from momentjs to check the validation of the input data. If the date in the input field is in the wrong format, it will show a “Wrong format” output, or else it will show, “Correct format”.

 

 

This is how we can validate the date in ReactJS.

Validate A Strong Password in ReactJS

  • Create an input field, add a state function and add onChange method on that input field just like the mentioned steps in the above section.
import React, { useState } from "react";

const App = () => {
  const [password, setPassword] = useState('')


  return (
    <div className="min-h-screen flex justify-center items-center">
      <input type="text" placeholder="Password" class="input input-bordered w-full max-w-xs bg-white text-black" onChange={(e) => setPassword(e.target.value)} />

    </div>
  );
}

export default App

Note: For now, we are keeping the input type as ‘text’. But it should be changed as ‘password’ in practical cases.

  • Use Regex for checking if the password contains a minimum of one capital letter in English, a minimum of one small letter in English, a minimum of one special character(.,// etc.), and a minimum of eight in length. (^(?=.*?[A-Z])(?=(.*[a-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W]){1,})(?!.*\s).{8,}$)
  • Write the below code in App.js
import React, { useEffect, useState } from "react";

const App = () => {
  const [password, setPassword] = useState('');
  const [strongPassword, setStrongPassword] = useState(false);


  useEffect(() => {
    // declaring regular expression for checking password
    const regeEx = /^(?=.*?[A-Z])(?=(.*[a-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W]){1,})(?!.*\s).{8,}$/;

    // test whether the password is strong enough or not
    if (regeEx.test(password)) {
      setStrongPassword(true)
    }
    else {
      setStrongPassword(false)
    }
  }, [password])

  return (
    <div className="min-h-screen flex justify-center items-center">
      <input type="text" placeholder="Password" class="input input-bordered w-full max-w-xs bg-white text-black" onChange={(e) => setPassword(e.target.value)} />
      <div>
        {
          strongPassword ? <p className="text-green-300">Password is strong enough</p> : <p className="text-red-500">Type a strong password</p>
        }
      </div>
    </div>
  );
}

export default App

Validate Email in ReactJS

To validate email in ReactJS we can use regular expression as well just like the previous section (to validate password)

// regular expression for validate email
/^\S+@\S+\.\S+$/
<input type="email" placeholder="Email" />
import React, { useEffect, useState } from "react";

const App = () => {
  const [email, setEmail] = useState('');
  const [correctFormat, setCorrectFormat] = useState(false);


  useEffect(() => {
    // declaring regular expression for checking email
    const regeEx = /^\S+@\S+\.\S+$/;

    // test whether the email format is okay or not
    if (regeEx.test(email)) {
      setCorrectFormat(true)
    }
    else {
      setCorrectFormat(false)
    }
  }, [email])

  return (
    <div className="min-h-screen flex justify-center items-center">
      <input onChange={e => setEmail(e.target.value)} type="email" placeholder="Email" class="input input-bordered w-full max-w-xs bg-white text-black" />
      <div>
        {
          correctFormat ? <p className="text-green-300">Correct format</p> : <p className="text-red-500">Wrong format</p>
        }
      </div>{

      }

    </div>
  );
}

export default App

These are the steps that we can take to validate the date, email and password.