How to validate a phone/ mobile number in the react js form; In this tutorial, you will learn how to validate the phone number using the regex pattern in React application. We will use the regex pattern to validate the phone number value in JavaScript.
What is ReGEX or Rational Expression?
The Regex is the short form of regular or rational expression string, it represents a combination of characters to filter on the string provided. The regex expression performs a search algorithm operation on the input value and returns the output based on validation.
A regex pattern is used to validate a string for its required format. it is mainly used to validate values like phone numbers, email addresses, website URLs etc.
Phone/ Mobile Validation in React App
In this guide, you will learn how to validate the phone number in React application. The input form fields will validate the value if it’s a valid phone number string or not.
We will create a reusable abstracted component to take a phone and return its validation status to the parent component.
Adding Phone/ Mobile ReGEX Validation in React App
- Step 1 – Create React App
- Step 2 – Add Bootstrap (Optional)
- Step 3 – Create Phone Validation Component
- Step 4 – Using Phone Input in App.js
- Step 5 – See in Action
Step 1 – Create React App
if you already have an app, skip this step. Else execute the below command to download and create a new react application.
npx create-react-app react-phone-validation-app
Move inside the application root
cd react-phone-validation-app
Step 2 – Add Bootstrap (Optional)
Adding bootstrap is optional. You can install it in your app by executing the below command:
npm install bootstrap
Now, import the bootstrap.min.css file in the main App.js component:
import React from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
export default function App() {
return (
<div className="container">
...
</div>
);
}
Step 3 – Create Phone Validation Component
Now, we will create a reusable Phone Validation component, that will maintain an internal state as well as emit the validation status to the parent component via a prop callback function.
Head towards the src folder and create a new file named form-phone-validation.js with the final location as ~src/form-phone-validation.js with the following code in it:
import React from "react";
class FormPhoneComponent extends React.Component {
constructor() {
super();
this.state = {
phone: "",
isvalid: false,
message: "",
};
this.onChange = this.onChange.bind(this);
}
onChange(e) {
this.setState({
phone: e.target.value,
});
}
phoneValidation() {
const regex = /^([+]?[\s0-9]+)?(\d{3}|[(]?[0-9]+[)])?([-]?[\s]?[0-9])+$/i;
return !(!this.state.phone || regex.test(this.state.phone) === false);
}
onSubmit() {
const isPhoneValid = this.phoneValidation();
this.setState(
{
isvalid: isPhoneValid,
message: isPhoneValid
? "Phone Number is Valid!"
: "Phone Number not valid!",
},
() => this.props.onPhoneSubmit(this.state)
);
// Check if email is valid
if (this.state.isvalid) {
console.log(this.state);
}
}
render() {
const messageTemplate = this.state.message ? (
<div
className={"alert alert-" + (this.state.isvalid ? "success" : "danger")}
role="alert"
>
{this.state.message}
</div>
) : (
""
);
return (
<div className="child-component">
<div className="form-group mb-3">
<label>
<strong>Phone</strong>
</label>
<input
type="phone"
name="phone"
value={this.state.phone}
onChange={this.onChange}
className="form-control"
/>
</div>
<div className="d-grid">
<button
type="submit"
className="btn btn-primary"
onClick={() => this.onSubmit()}
>
Submit
</button>
</div>
<br />
{messageTemplate}
</div>
);
}
}
export default FormPhoneComponent;
The internal state is carrying phone
, isvalid
and message
variable to depict the input phone control validation state.
The class component is having a phoneValidation() function which is validating the email variable in the state and returning true or false after matching the string to the provided Regex pattern.
The onChange() function is called when the input phone control value is changed and updated the state’s phone variable.
The onSubmit() function is doing heavy-load stuff, by updating the internal state and also passing back via props.onPhoneSubmit() to the parent.
One thing to note is we’re using the callback of setState due to its asynchronous behaviour. if you skip such implementation, you will notice the parent is not getting the updated state
Step 4 – Using Phone Input in App.js
Now, adding the FormPhoneComponent
in the App.js file and also passing the onPhoneSubmit callback props to fetch child’s state.
Open App.js file and update it with the following code:
import React, { useEffect } from "react";
import { useState } from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import FormPhoneComponent from "./form-phone-validation";
export default function App() {
const [phonestatus, setPhonestatus] = useState({});
function onSubmit(res) {
setPhonestatus(res);
}
useEffect(() => {
console.log("From App.js ", phonestatus);
}, [phonestatus]);
return (
<div className="container parent-component">
<h1>Phone Validation ReGEX in React @ FreakyJolly.com</h1>
{JSON.stringify(phonestatus)}
<FormPhoneComponent onPhoneSubmit={onSubmit} />
</div>
);
}
To reflect the updated state of the App component, we used useEffect hook, it will help to reflect the latest state. Otherwise, you won’t be able to see immediate changes in the state due to its asynchronous behaviour as we discussed earlier in the case of the class component as well.
As a part of the Parent and Child border style, to make it more distinguishable, I added the following style in the App.css file. This one is optional stuff. Just added to make thing more clear at first glance 🙂
.parent-component{
border: 2px solid #60c760;
padding: 10px;
margin:10px;
}
.parent-component::before{
content: "Parent Component";
}
.child-component{
border: 2px solid #ff8b8b;
padding: 10px;
margin:10px;
}
.child-component::before{
content: "Child Component";
}
Step 5 – See in Action
Finally, you can run the application by hitting npm start
to start the application at the following URL:
http://localhost:3000
Check working demo @ StackBlitz here:
Leave a Reply