
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Validate URL in ReactJS
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 −
Valid URL − https://www.tutorialspoint.com/
Invalid URL − https://www.tutorialspoint
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.