How to useJavaScript Regular Expression in React JS in ReactJS
Implement a regular expression for input length to validate the mobile number input. This regular expresstion will return false if the input length is more than 10 digits and true if length is valid.
Example: This example implemets a form with mobile number input field validated using regex.
Javascript
// Filename - App.js import React, { useState } from "react" ; const App = () => { const [mobile, setmobile] = useState( "" ); const [isError, setIsError] = useState( false ); const pattern = new RegExp(/^\d{1,10}$/); return ( <div style={{ margin: "auto" , textAlign: "center" , }} > <h1 style={{ color: "green" }}> w3wiki </h1> <h3> Validate Mobile number length in ReactJS? </h3> <input value={mobile} type= "number" placeholder= "Enter mobile number" onChange={(e) => { setmobile(e.target.value); if (!pattern.test(e.target.value)) setIsError( true ); else setIsError( false ); }} /> <h3> Your Mobile Number is: {isError ? "Invalid" : "+91" + mobile} </h3> </div> ); }; export default App; |
Steps to run the applicaition: Use this command to run the output
npm start
Output: This output will be visible on http://localhost:3000/ on browser window.
How to validate mobile number length in ReactJS ?
Validating mobile number length in React JS App is an important step to check whether the number entered by the user is genuine or not. It is effective in many case like creating a user form, collection of employee details, etc.
Approaches to validate mobile number length in React Js are
Table of Content
- Using JavaScript Regular Expression in React JS
- Using Material UI component
Contact Us