RegEx in ReactJS

ReactJSWeb DevelopmentFront End Technology

In this article, we are going to see how to handle the strings with RegEx handling in a React application.

A RegEx or Regular Expression is a sequence of characters that forms a search pattern and is used to check if a string contains a specified search pattern or not. It is also used to validate strings which consist of email, passwords etc.

Syntax

new RegExp(pattern[, flags])

Example

In this example, we will build an authentication React application that takes an email and password from the user and checks if they are validated or not.

We have Regex.js which contains all the regular expressions to validate the email and password for our application.

Regex.jsx

export const validEmail = new RegExp(
   '^[a-zA-Z0-9._:$!%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]$'
);
export const validPassword = new RegExp('^(?=.*?[A-Za-z])(?=.*?[0-9]).{6,}$');

App.jsx

import React, { useState } from 'react';
import { validEmail, validPassword } from './regex.js';

const App = () => {
   const [email, setEmail] = useState('');
   const [password, setPassword] = useState('');
   const [emailErr, setEmailErr] = useState(false);
   const [pwdError, setPwdError] = useState(false);
   const validate = () => {
      if (!validEmail.test(email)) {
         setEmailErr(true);
      }
      if (!validPassword.test(password)) {
         setPwdError(true);
      }
   };
   return (
      <div>
         <input
            type="email"
            placeholder="Email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
         />
         <input
            type="password"
            placeholder="Password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
         />
         <div>
            <button onClick={validate}>Validate
         </div>
         {emailErr && <p>Your email is invalid</p>}
         {pwdError && <p>Your password is invalid</p>}
      </div>
   );
};
export default App;

In the above example, when the user clicks the Validate button, it checks for the validity of the email and password and displays the result accordingly.

Output

This will produce the following result.

raja
Published on 19-Mar-2021 11:05:09
Advertisements