In this tutorial, you will learn how to validate URLs using regular expressions in ReactJS.
How to validate URL using Regular Expression in React JS
Steps to create a form component with URL input fields and apply regex patterns for valid URL matching:
Step 1 – Create React App
Run the following command on your terminal to create a new react app:
npx create-react-app my-react-app
To run the React app, execute the following command on your terminal:
npm start
Check out your React app on this URL: localhost:3000
Step 2 – Create a Simple Component
Visit the src
directory of your react js app, create url validation with a regular expression component named UrlComponent.js, and add the following code into it:
import React, { Component } from "react"; class UrlComponent extends Component { state = { URL: "", isTrueVal: false }; urlPatternValidation = URL => { const regex = new RegExp('(https?://)?([\\da-z.-]+)\\.([a-z.]{2,6})[/\\w .-]*/?'); return regex.test(URL); }; changeUrl = event => { const { value } = event.target; const isTrueVal = !value || this.urlPatternValidation(value); this.setState({ URL: value, isTrueVal }); }; onSubmit = () => { const { URL } = this.state; console.log("Here is the site url: ", URL); }; render() { const { isTrueVal, URL } = this.state; return ( <div> <form> <input type="text" name="URL" value={URL} onChange={this.changeUrl} /> {!this.state.isTrueVal && ( <div style={{ color: "#F61C04" }}>URL is not valid.</div> )} <button onClick={this.onSubmit} disabled={!isTrueVal}>Store</button> </form> </div> ); } } export default UrlComponent;
Step 3 – Add Component in App.js
In this step, you need to add UrlComponent .js file in src/App.js
file:
import React from 'react'; import './App.css'; import UrlComponent from './components/UrlComponent'; function App() { return ( <div className="App"> <UrlComponent /> </div> ); } export default App;
Conclusion
In this tutorial, you have learned how URL validation is integrated into react js.