Reputation: 16793
I am trying to implement uri validation as follows.
For the sake of testing, I assigned my url
as an empty string ""
, and tested the following code, but it returns me True.
I wonder what I am doing wrong/missing?
var a = "";
if (Uri.IsWellFormedUriString(a, UriKind.RelativeOrAbsolute))
{
Debug.WriteLine("True");
}
else
{
Debug.WriteLine("Error");
}
Upvotes: 0
Views: 3608
Reputation: 64923
See what RFC2396 says about URIs:
4.2. Same-document References
A URI reference that does not contain a URI is a reference to the
current document. In other words, an empty URI reference within a
document is interpreted as a reference to the start of that document, and a reference containing only a fragment identifier is a reference
to the identified fragment of that document. Traversal of such a
reference should not result in an additional retrieval action.
However, if the URI reference occurs in a context that is always
intended to result in a new request, as in the case of HTML's FORM
element, then an empty URI reference represents the base URI of the
current document and should be replaced by that URI when transformed
into a request.
Casually, see what MSDN says:
The string is considered to be well-formed in accordance with RFC 2396 and RFC 2732 by default. If International Resource Identifiers (IRIs) or Internationalized Domain Name (IDN) parsing is enabled, the string is considered to be well-formed in accordance with RFC 3986 and RFC 3987
The answer is up to you. While an empty URI can be considered as valid, maybe in your scenario isn't valid. Thus, you need to add a condition in your if
statement:
if (!string.IsNullOrEmpty(a) && Uri.IsWellFormedUriString(a, UriKind.RelativeOrAbsolute))
{
}
Upvotes: 1