Validating URL using Validation attribute

When a user enters an URL in a TextBox, the URL needs to be validated. Validation attributes can be used to check if the URL is live.

The Url property is part of an entity object. UrlValid is derived from ValidationAttribute. ValidationAttribute is the base class for RequiredAttribute, CompareAttribute, StringLengthAttribute, DataTypeAttribute, and RegularExpressionAttribute. The IsValid method of ValidationAttribute should be overridden.

Within the IsValid method, HttpWebRequest class is used to check if the URL is live. If there any exceptions in getting the response, IsValid returns false. If the status code of the response does not belong to a successful status code (200 OK), IsValid returns false.

The above code needs to be modified depending on the environment in which it is used. Within an intranet, the HttpWebRequest requires network credentials to function. For some scenarios, a Redirect status code is not acceptable. In some cases, the exception thrown by HttpWebRequest needs to be analyzed for providing a better message to the end user.

Leave a Reply

Your email address will not be published. Required fields are marked *