React Js Validate URL using Regular Expression Example

React Js Validate URL using Regular Expression Example

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

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *