A registration form contains many fields to get the user information, In this tutorial, we will see How to validate the registration form in ReactJS that contains the input fields username, email, password, date of birth, etc.
Learnings
- Validate username in reactJS
- Validate Email in reactJS
- Validate password in reactJS
- Validate DOB in reactJS
To keep the application secure, the input data should be valid and it should be in the required format. while filling up a registration form whether the data that the user has written fulfilled the required conditions or not.
But before that, we have to set up the environment. To know about creating a project, please read this article.
Setup the environment to create a registration page in reactJS
- Run the below commands in the command prompt to create a react project
npx create-react-app my-app cd my-app npm start
- Open the App.js file which is inside the src folder inside the newly created react app.
import React, { useState, useEffect } from "react"; const App = () => { return ( <div> </div> ); } export default App
Whatever we write inside this div
that this app function is returning, will be visible to the browser.
Now that the environment is ready, we can proceed with the validation part.
Validate username in ReactJS
In the username validation process, we are requiring the user to add a username that will
- Contain only alphanumeric characters, underscore, and dot.
- The number of characters must be between 8 to 20.
- Underscore or dot can’t be used multiple times in a row.
We will validate these conditions using the regular expression,
^(?=[a-zA-Z0-9._]{8,20}$)(?!.*[_.]{2})[^_.].*[^_.]$
Below are the steps that we will follow to validate the username according to our condition.
- Create a form containing some input to add username, email, password, and DOB.
import React, { useState, useEffect } from "react"; const App = () => { return ( <div className="w-2/3 mx-auto"> <form class="card-body my-20 p-0"> <div className="form-control items-center lg:items-start"> <input type="text" placeholder="user name" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start"> <input required type="password" placeholder="password" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start"> <input type="email" placeholder="email" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start"> <input type="date" placeholder="DOB" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start mt-6"> <button type="submit" className="btn btn-sm w-full max-w-md">Register</button> </div> </form> </div> ); } export default App
After creating the form with the required field, it will look like this.
Note: we are using Tailwind CSS to use styled class. Read this article to know more about this.
- Declare a state and create an
onChange
() event to the username input; so that the username can be saved on the state with each key change.
<div className="form-control items-center lg:items-start"> <input onChange={(e) => setUserName(e.target.value)} type="text" placeholder="user name" className="input input-bordered w-full max-w-md " /> </div>
// state for username const [userName, setUserName] = useState(''); console.log(userName)
import React, { useState, useEffect } from "react"; const App = () => { // state for username const [userName, setUserName] = useState(''); console.log(userName) return ( <div className="w-2/3 mx-auto"> <form class="card-body my-20 p-0"> <div className="form-control items-center lg:items-start"> <input onChange={(e) => setUserName(e.target.value)} type="text" placeholder="user name" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start"> <input required type="password" placeholder="password" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start"> <input type="email" placeholder="email" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start"> <input type="date" placeholder="DOB" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start mt-6"> <button type="submit" className="btn btn-sm w-full max-w-md">Register</button> </div> </form> </div> ); } export default App
As we can see whatever character the user enters, can be checked with this onChange event.
- Validate this
userName
state with the regex value.
const [validate, setValidate] = useState(false); // state for username const [userName, setUserName] = useState(''); const checkRegexForUsername = (/^(?=[a-zA-Z0-9._]{8,20}$)(?!.*[_.]{2})[^_.].*[^_.]$/).test(userName); useEffect(() => { if (!checkRegexForUsername) { setValidate(false); } else { setValidate(true) } }, [checkRegexForUsername])
Here we are validating whether the username meets our conditions or not. If not, then we are setting the validate state as false. Based on this boolean value, we will disable the register button below the form. So that if the conditions don’t meet the requirement, the user can’t click the button.
import React, { useState, useEffect } from "react"; const App = () => { const [validate, setValidate] = useState(false); // state for username const [userName, setUserName] = useState(''); const checkRegexForUsername = (/^(?=[a-zA-Z0-9._]{8,20}$)(?!.*[_.]{2})[^_.].*[^_.]$/).test(userName); useEffect(() => { if (!checkRegexForUsername) { setValidate(false); } else { setValidate(true) } }, [checkRegexForUsername]) return ( <div className="w-2/3 mx-auto"> <form class="card-body my-20 p-0"> <div className="form-control items-center lg:items-start"> <input onChange={(e) => setUserName(e.target.value)} type="text" placeholder="user name" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start"> <input required type="password" placeholder="password" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start"> <input type="email" placeholder="email" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start"> <input type="date" placeholder="DOB" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start mt-6"> <button disabled={!validate} type="submit" className="btn btn-sm w-full max-w-md">Register</button> </div> </form> </div> ); } export default App
In the same way, we will validate emails and others.
Validate Email in ReactJS
- Below is the regex for validating email,
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
- Declare a state and onChange event for the email input field as well and test out the typed value with the regex
// state for email const [email, setEmail] = useState('') const checkRegexForEmail = (/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(email); console.log(checkRegexForEmail) useEffect(() => { if (!checkRegexForUsername || !checkRegexForEmail) { setValidate(false); } else { setValidate(true) } }, [checkRegexForUsername, checkRegexForEmail])
import React, { useState, useEffect } from "react"; const App = () => { const [validate, setValidate] = useState(false); // state for username const [userName, setUserName] = useState(''); const checkRegexForUsername = (/^(?=[a-zA-Z0-9._]{8,20}$)(?!.*[_.]{2})[^_.].*[^_.]$/).test(userName); // state for email const [email, setEmail] = useState('') const checkRegexForEmail = (/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(email); console.log(checkRegexForEmail) useEffect(() => { if (!checkRegexForUsername || !checkRegexForEmail) { setValidate(false); } else { setValidate(true) } }, [checkRegexForUsername, checkRegexForEmail]) return ( <div className="w-2/3 mx-auto"> <form class="card-body my-20 p-0"> <div className="form-control items-center lg:items-start"> <input onChange={(e) => setUserName(e.target.value)} type="text" placeholder="user name" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start"> <input required type="password" placeholder="password" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start"> <input onChange={e => setEmail(e.target.value)} type="email" placeholder="email" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start"> <input type="date" placeholder="DOB" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start mt-6"> <button disabled={!validate} type="submit" className="btn btn-sm w-full max-w-md">Register</button> </div> </form> </div> ); } export default App
Validate password in ReactJS
We will use the below regex to validate the password. Below regex will check whether the password contains a minimum of eight characters with at least a symbol, upper and lower case letters, and a number.
/^(?=.*\d)(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,}$/
- Declare a state to get the onChange value from the password input field.
<div className="form-control items-center lg:items-start"> <input onChange={e => setPassword(e.target.value)} required type="password" placeholder="password" className="input input-bordered w-full max-w-md " /> </div>
// state for password const [password, setPassword] = useState('');
- Validate the password whether it fulfills the requirement or not.
// state for password const [password, setPassword] = useState(''); const checkRegexForPassword = (/^(?=.*\d)(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,}$/).test(password);
- Show an error (disable the register button) based on fulfilling the requirements or not.
useEffect(() => { if (!checkRegexForUsername || !checkRegexForEmail || !checkRegexForPassword) { setValidate(false); } else { setValidate(true) } }, [checkRegexForUsername, checkRegexForEmail, checkRegexForPassword])
import React, { useState, useEffect } from "react"; const App = () => { const [validate, setValidate] = useState(false); // state for username const [userName, setUserName] = useState(''); const checkRegexForUsername = (/^(?=[a-zA-Z0-9._]{8,20}$)(?!.*[_.]{2})[^_.].*[^_.]$/).test(userName); // state for email const [email, setEmail] = useState('') const checkRegexForEmail = (/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(email); // state for password const [password, setPassword] = useState(''); const checkRegexForPassword = (/^(?=.*\d)(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,}$/).test(password); useEffect(() => { if (!checkRegexForUsername || !checkRegexForEmail || !checkRegexForPassword) { setValidate(false); } else { setValidate(true) } }, [checkRegexForUsername, checkRegexForEmail, checkRegexForPassword]) return ( <div className="w-2/3 mx-auto"> <form class="card-body my-20 p-0"> <div className="form-control items-center lg:items-start"> <input onChange={(e) => setUserName(e.target.value)} type="text" placeholder="user name" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start"> <input onChange={e => setPassword(e.target.value)} required type="password" placeholder="password" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start"> <input onChange={e => setEmail(e.target.value)} type="email" placeholder="email" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start"> <input type="date" placeholder="DOB" className="input input-bordered w-full max-w-md " /> </div> <div className="form-control items-center lg:items-start mt-6"> <button disabled={!validate} type="submit" className="btn btn-sm w-full max-w-md">Register</button> </div> </form> </div> ); } export default App
As we can see, after validating according to the requirements, the button appears and the user can click on it.
Validate Date in ReactJS
We can check whether the date value has been selected or not.
- Declare an onChange event and a state to store the selected date.
<div className="form-control items-center lg:items-start"> <input onChange={e => setDate(e.target.value)} type="date" placeholder="DOB" className="input input-bordered w-full max-w-md " /> </div>
// state for date const [date, setDate] = useState(''); useEffect(() => { if (!checkRegexForUsername || !checkRegexForEmail || !checkRegexForPassword || !date) { setValidate(false); } else { setValidate(true) } }, [checkRegexForUsername, checkRegexForEmail, checkRegexForPassword, date])
Here, we have set the input type as the date. So it will by default take only valid date value. And we will disable the button if the date value too not entered.
After fulfilling every condition and validation, the button will appear and the user can click on it.
This is how we can validate some input fields based on some required conditions in ReactJS.