Home > Backend Development > C++ > How Can I Reliably Validate HTTP and HTTPS URLs in Input?

How Can I Reliably Validate HTTP and HTTPS URLs in Input?

Patricia Arquette
Release: 2025-01-09 14:08:42
Original
338 people have browsed it

How Can I Reliably Validate HTTP and HTTPS URLs in Input?

Robust Input Validation for HTTP and HTTPS URLs

Common URL validation methods like Uri.IsWellFormedUriString and Uri.TryCreate sometimes fail to reliably distinguish valid HTTP URLs from other file paths. This presents a significant challenge when validating user input where only HTTP or HTTPS URLs are acceptable.

A More Accurate Approach: Combining URI Validation and Scheme Checking

A more robust solution involves combining structural URI validation with a specific check for the HTTP or HTTPS scheme:

Uri uriResult;
bool isValidHttpUrl = Uri.TryCreate(uriString, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
Copy after login

This code first uses Uri.TryCreate to verify the input string (uriString) as a well-formed URI. If successful, it then checks if the URI's scheme is Uri.UriSchemeHttp.

Extending Validation to Include HTTPS

To include HTTPS URLs, simply expand the scheme comparison:

Uri uriResult;
bool isValidHttpOrHttpsUrl = Uri.TryCreate(uriString, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
Copy after login

This enhanced check accepts both HTTP and HTTPS protocols, providing comprehensive URL validation for your input.

The above is the detailed content of How Can I Reliably Validate HTTP and HTTPS URLs in Input?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template