can some one tell me how can i validate a url like http://www.abc.com
Uri.IsWellFormedUriString checks that the URL format is correct and does not require escaping.
/// <summary>
/// Ensures the property is a valid URL.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class ValidateUrlAttribute : ValidationAttribute
{
public ValidateUrlAttribute()
{
}
public override bool IsValid(object value)
{
// Do not validate missing URLs - people can use [Required] for that.
string text = (value as string) ?? "";
if (text == "")
return true;
return Uri.IsWellFormedUriString(text, UriKind.Absolute);
}
}
Let the System.Uri do the heavy lifting for you, instead of a RegEx:
public class UrlAttribute : ValidationAttribute
{
public UrlAttribute()
{
}
public override bool IsValid(object value)
{
var text = value as string;
Uri uri;
return (!string.IsNullOrWhiteSpace(text) && Uri.TryCreate(text, UriKind.Absolute, out uri ));
}
}
I use this regular expression for Internal or external URLS on my site.
((?:https?\:\/\/|\/.)(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)