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

OR

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.

Example

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.

App.jsx

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

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

   const validate = (e) => {
      setVal(e.target.value);
      if (isURL(val)) {
         setErr('Valid URL');
      } else {
         setErr('Invalid URL');
      }
   };
   return (
      <div>
         <h2>Tutorialspoint</h2>
         <h3>Enter URL for validation: </h3>
         <input value={val} onChange={validate} />
         <p>{err}</p>
      </div>
   );
};
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.

Output

This will produce the following result.

raja
Published on 19-Mar-2021 11:14:37
Advertisements