Thursday, July 4, 2024
HomeLanguagesJavascriptHow to validate URL in ReactJS?

How to validate URL in ReactJS?

URL (Uniform Resource Locator) is a reference/address to a resource on the Internet. For example, www.neveropen.com is a URL. The following example shows how to validate the user entered data and check whether it is valid or not using the npm module in the ReactJS application. 

Creating React Application And Installing Module:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Step 3: After creating the ReactJS application, Install the validator module using the following command:

npm install validator

Project Structure: It will look like the following.

Project Structure

App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

Javascript




import React, { useState } from "react";
import validator from 'validator'
  
const App = () => {
  
  const [errorMessage, setErrorMessage] = useState('')
    
  const validate = (value) => {
    
    if (validator.isURL(value)) {
      setErrorMessage('Is Valid URL')
    } else {
      setErrorMessage('Is Not Valid URL')
    }
  }
  
  return (
    <div style={{
      marginLeft: '200px',
    }}>
      <pre>
        <h2>Validating URL in ReactJS</h2>
        <span>Enter URL: </span><input type="text" 
        onChange={(e) => validate(e.target.value)}></input> <br />
        <span style={{
          fontWeight: 'bold',
          color: 'red',
        }}>{errorMessage}</span>
      </pre>
    </div>
  );
}
  
export default App


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

  • The following will be the output if the user enters an invalid URL as shown below:

  • The following will be the output if the user enters a valid URL as shown below:

Thapelo Manthata
I’m a desktop support specialist transitioning into a SharePoint developer role by day and Software Engineering student by night. My superpowers include customer service, coding, the Microsoft office 365 suite including SharePoint and power platform.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments