How to Check if a URL is Valid

87 views

How to Check if a URL is Valid

How to Check if a URL is Valid

I need to validate whether a URL entered by a user is in a correct format. How can I do this?

solveurit24@gmail.com Changed status to publish February 16, 2025
0

You can use a regular expression to validate the URL format.

Code Example:

import re

def is_valid_url(url):
    pattern = (
        r'^https?://'  # http:// or https://
        r'([a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+)'  # domain name
        r'(:\d+)?'  # optional port number
        r'(\/.*)?$'  # optional path
    )
    return re.match(pattern, url) is not None

# Example usage
print(is_valid_url("https://www.example.com"))  # Output: True
print(is_valid_url("ftp://invalid.url"))       # Output: False

This function uses a regex pattern to determine if the given URL has the correct format.

solveurit24@gmail.com Changed status to publish February 16, 2025
0
You are viewing 1 out of 1 answers, click here to view all answers.