URL Data Annotation Validator in ASP.NET MVC: A Tutorial with Code Example. As an ASP .NET MVC developer, you may have come across situations where you need to validate URLs in your web applications. For instance, when accepting user input, you want to ensure that the URLs provided are valid and correct.
To achieve this, you can use the URL validator data annotation in ASP .NET MVC. This validation attribute checks whether a string value represents a valid URL, ensuring that it conforms to the HTTP or HTTPS URL schemes.
How to Use the URL Validator Data Annotation
The URL validator data annotation is easy to use in your ASP .NET MVC applications. To validate a URL in a model property, you simply add the [Url] attribute to the property's definition, like this:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
[Url(ErrorMessage = "Please enter a valid URL")]
public string ProductLink { get; set; }
}
In the code above, we have added the [Url] attribute to the ProductLink property, which is the URL field we want to validate. We also provided an error message to display when the validation fails.
When the user submits the form, the ASP .NET MVC model binder automatically checks the value of the ProductLink field to ensure that it is a valid URL. If the URL is invalid, the ModelState object will be marked as invalid, and the error message specified in the attribute will be displayed.
Customizing the URL Validation
You can also customize the URL validation to match your specific requirements. For instance, you can enforce specific URL schemes, such as only allowing HTTP or HTTPS URLs. To achieve this, you can add the RequireHttps attribute, which ensures that the URL must start with the HTTPS scheme.
[Url(ErrorMessage = "Please enter a valid URL")]
[RequireHttps(ErrorMessage = "Please enter a secure URL")]
public string ProductLink { get; set; }
In the example above, we have added the [RequireHttps] attribute to the ProductLink property, which means that the URL must start with the HTTPS scheme.
Conclusion
The URL validator data annotation in ASP .NET MVC provides an easy and convenient way to validate URLs in your web applications. By adding the [Url] attribute to a model property, you can ensure that the URL is valid, and customize the validation to meet your specific requirements. With this, you can make your web applications more secure and reliable.