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.

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.

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.

Validating URL using Validation attribute
Tagged on: