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
Patricia ArquetteOriginal
2025-01-09 14:08:42321browse

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:

<code class="language-csharp">Uri uriResult;
bool isValidHttpUrl = Uri.TryCreate(uriString, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;</code>

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:

<code class="language-csharp">Uri uriResult;
bool isValidHttpOrHttpsUrl = Uri.TryCreate(uriString, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);</code>

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:
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