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;
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);
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!