Validate URL in ReactJS

ReactJSWeb DevelopmentFront End Technology

In this article, we are going to see how to validate a URL (Uniform Resource Locator) in a React application.

To validate a URL, we are going to install a third-party package of ‘validator’ which is used to validate the URL. Example of a valid and an invalid URL are as follows −

Installing the module

npm install validator


yarn add validator

Npm is the node package manager which manages our React package but yarn is the more secure, faster and lightweight package manager.


In this example, we will build a React application which takes a URL input from the user and checks if it is a valid URL or not.


import React, { useState } from 'react';
import isURL from 'validator/lib/isURL';

const App = () => {
   const [val, setVal] = useState('');
   const [err, setErr] = useState('');

   const validate = (e) => {
      if (isURL(val)) {
         setErr('Valid URL');
      } else {
         setErr('Invalid URL');
   return (
         <h3>Enter URL for validation: </h3>
         <input value={val} onChange={validate} />
export default App;

In the above example, whenever the user types a character, it is checked if it is a valid URL or not and then the error message is displayed accordingly.


This will produce the following result.

Updated on 19-Mar-2021 11:15:50