Comprehensive Guide to Valid-URL with Examples and Applications for SEO Optimization

Introduction to Valid-URL

Valid-URL is a powerful library used to validate URLs, ensuring they adhere to standard URL syntax and structure. In this guide, we’ll explore its usage, different APIs, provide code snippets, and showcase an app example utilizing these APIs effectively.

API Overview

Basic URL Validation

This basic function checks if a given string is a valid URL.

  
    const validUrl = require('valid-url');

    if (validUrl.isUri('http://www.google.com')) {
      console.log('The URL is valid');
    } else {
      console.log('The URL is invalid');
    }
  

Validate HTTP or HTTPS URL

This function validates if a URL is either HTTP or HTTPS.

  
    if (validUrl.isHttpUri('http://www.example.com')) {
      console.log('The URI is a valid HTTP URL');
    } else {
      console.log('The URI is invalid');
    }

    if (validUrl.isHttpsUri('https://www.example.com')) {
      console.log('The URI is a valid HTTPS URL');
    } else {
      console.log('The URI is invalid');
    }
  

Validate Web Resource URL

This function checks if a URL points to a web resource.

  
    if (validUrl.isWebUri('http://www.example.com/resource')) {
      console.log('The URI is a valid web resource URL');
    } else {
      console.log('The URI is invalid');
    }
  

Example App Using Valid-URL

Below is an example of an Express.js app that uses valid-url to validate URLs submitted through a form.

  
    const express = require('express');
    const bodyParser = require('body-parser');
    const validUrl = require('valid-url');

    const app = express();
    app.use(bodyParser.urlencoded({ extended: true }));

    app.get('/', (req, res) => {
      res.send(`
        <form action="/validate" method="post">
          <label for="url">Enter URL:</label>
          <input id="url" type="text" name="url">
          <button type="submit">Validate</button>
        </form>
      `);
    });

    app.post('/validate', (req, res) => {
      const url = req.body.url;

      if (validUrl.isUri(url)) {
        res.send('The URL is valid.');
      } else {
        res.send('The URL is invalid.');
      }
    });

    app.listen(3000, () => {
      console.log('Server is running on port 3000');
    });
  

By understanding and utilizing valid-url’s capabilities, developers can efficiently validate URLs within their applications, ensuring better data integrity and user experience.


Hash: ddd039e0562b703a34fc724cecc08e494c3b1a619e3d0de26dcc2366ad4b888d

Leave a Reply

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