React Js Validate URL using Regular Expression Example

import React, { useState } from ‘react’;

const ValidateURL = () => {
const [url, setUrl] = useState(”);
const [valid, setValid] = useState(false);

const handleChange = (e) => {
setUrl(e.target.value);
};

const handleSubmit = (e) => {
e.preventDefault();
const regex = /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:[/?#]\S*)?$/i;
setValid(regex.test(url));
};

return (



{valid ?

Valid URL

:

Invalid URL

}

);
};

export default ValidateURL;

To validate the URL in react js with regular expression; In this tutorial, you will learn how to validate URLs using regular expressions in ReactJS. This is a useful skill to have if you are building web applications that require user input and need to ensure that the input is a valid URL.

How to validate URL in React JS

Follow the following steps and validate url in react js app:

  • Step 1 – Create React App
  • Step 2 – Create Simple Component
  • Step 3 – Add Component in App.js

Step 1 – Create React App

In this step, open your terminal and execute 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 Simple Component

Visit the src directory of your react js app and 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;

Here is a breakdown of above given code:

This code is a React component that creates a form with an input field and a submit button. It allows the user to enter a URL into the input field, and when the user clicks the submit button, it logs the URL to the console.

  • The first line of the code imports the React library and the Component class from the “react” module. This is necessary to create a React component.
  • The UrlComponent class is defined next, which extends the Component class from the React library. The class defines a state object with two properties: URL and isTrueVal. The URL property stores the current value of the input field, and the isTrueVal property tracks whether the URL entered by the user is valid or not.
  • The urlPatternValidation function takes a URL as an argument and checks if it matches a regular expression pattern for a valid URL. If the URL matches the pattern, the function returns true, otherwise it returns false.
  • The changeUrl function is called every time the user types a character in the input field. It extracts the value of the input field and checks whether it matches the regular expression pattern using the urlPatternValidation function. If the value is empty or matches the pattern, the isTrueVal property of the state object is set to true, otherwise it is set to false. The URL property of the state object is also set to the current value of the input field.
  • The onSubmit function is called when the user clicks the submit button. It logs the current value of the URL property to the console.
  • In the render method, a form is created with an input field and a submit button. The value of the input field is set to the URL property of the state object, and the onChange event of the input field is set to the changeUrl function. If the isTrueVal property of the state object is false, a message is displayed below the input field to inform the user that the URL is not valid. The submit button is disabled if the isTrueVal property of the state object is false.

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. And as well as learned how to use RegEx and the test method to implement pattern match validation in react.

Recommended React JS Tutorials

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?