React Js Validate URL using Regular Expression Tutorial

Last updated on: by Editorial Team

React Js input URL validation tutorial; In this quick tutorial, you will learn how to implement URL validation in React js application using the JavaScript regular expression.

To validate the URL in react, we will use the RegEx() and test() methods along with react js state object. We will go through step by step to explain how to create the simple input type validation in react.

The RegEx() method is a handy method provided by JavaScript, commonly knows as a regular expression. It is an object that represents a pattern of characters and is ideally used for pattern-matching and “search-and-replace” functions for text.

On the other hand, the test() method tests a match in a string. If it detects a match, it returns true else return false.

How to Use Regular Expression to Validate URL in React Js

  • Step 1: Create React Project
  • Step 2: Create Component File
  • Step 3: Validate URL with Regular Expression
  • Step 4: Update App Js File
  • Step 5: Start React App

Create React Project

In the initial step, you have to install the new react application with the help of the “npx create” command.

npx create-react-app react-blog

As soon as the new app is installed, move into the project folder.

cd react-blog

Create Component File

You have to create a components/ folder; in this folder, create the UrlComponent.js file, then create the UrlComponent class.

import React, { Component } from "react";

class UrlComponent extends Component {
  render() {
    return (
      <div> </div>
    );
  }
}

export default UrlComponent;

Validate URL with Regular Expression in React

To integrate the image crop in react native, you have to add the provided code inside the components/UrlComponent.js file.

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;

Let’s understand the nuances of UrlComponent class, set the state with URL and isTrueVal, define the urlPatternValidation() function.

This function sets and checks the regular expression and returns a boolean value.

The changeUrl function helps update the state of URL and isTrueVal based on the value entered by the user. The render functions output the result and showing the error message when the user types value in the input field.

Update App Js File

Next, import the UrlComponent from ‘./components/UrlComponent’ and define the UrlComponent tag in the App function.

Open src/App.js and update the following code inside the file.

import React from 'react';
import './App.css';

import UrlComponent from './components/UrlComponent';

function App() {
  return (
    <div className="App">
      <UrlComponent />
    </div>
  );
}

export default App;

Start React App

In the final step, we must run the development server using the npm start command, so go ahead and evoke the following command.

npm start

After starting the development server, you may see the app on the browser:

http://localhost:3000

React Js Validate URL using Regular Expression Tutorial

Conclusion

In this tutorial, you have learned how URL validation is integrated into react js; we have also seen how to use RegEx and the test method to implement pattern match validation in react.