Validation in ASP.NET MVC is done by decorating model properties with attributes. There are some built-in validation attributes. For example, Required attribute ensures that there exists a value for the property. We can write custom validation attributes as well. In this post, we build a UrlValid
attribute. When the user enters an URL in a TextBox, the UrlValid
attribute verifies if the URL is active.
[UrlValid(ErrorMessage = "The URL entered is not live.")] public string Url { get; set; }
The Url property is part of a model. We decorate the property with UrlValid
attribute.
All custom attributes derive from ValidationAttribute. It is also the base class for RequiredAttribute
, CompareAttribute
, StringLengthAttribute
, DataTypeAttribute
and RegularExpressionAttribute
. Override the IsValid method
of ValidationAttribute
.
public class UrlValidAttribute : ValidationAttribute { public override bool IsValid(object value) { string url = (string)value; if (string.IsNullOrEmpty(url)) return true; HttpWebResponse res; try { Uri uri = new Uri(url, UriKind.Absolute); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri); res = (HttpWebResponse)req.GetResponse(); } catch { return false; } switch (res.StatusCode) { case HttpStatusCode.OK: case HttpStatusCode.Redirect: case HttpStatusCode.RedirectKeepVerb: case HttpStatusCode.RedirectMethod: return true; } return false; } }
Within the IsValid method, HttpWebRequest
class is used to check if the URL is active. If the URL is down, exceptions are thrown. And, IsValid
method returns false. In addition, we verify if the status code of the response is a successful status code (200 OK). For other status codes, IsValid
method returns false. The above code does not work smoothly in all network configurations. Within an intranet, the HttpWebRequest
requires network credentials to function.
Also, for some scenarios, analyze the response in greater detail. Redirect status code is sometimes not acceptable. We should also parse the exception thrown for providing a better message to the end user.