Compare Validator in ASP.NET MVC: A Tutorial with Code Examples. Data annotation is a feature in .NET MVC that allows developers to enforce validation rules on data models. This makes it easier to ensure that data entered into the application is consistent, accurate, and valid. In this blog post, we'll use compare data annotations in .NET MVC with a code example.
Let's compare the Compare data annotation with code examples.
Suppose we have a model class with two properties, "Password" and "ConfirmPassword". We want to ensure that these properties match. Here's an example of how we could do this using the Compare data annotation:
public class UserModel
{
[Required(ErrorMessage = "Password is required")]
public string Password { get; set; }
[Compare("Password", ErrorMessage = "Password and Confirm Password do not match")]
[Required(ErrorMessage = "Confirm Password is required")]
public string ConfirmPassword { get; set; }
}
Enable client side validation, you can check this:
Enable client side validation in ASP.NET MVC
Add this code to your view:
@model MVC_Testing.Controllers.UserModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.TextBoxFor(x => x.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.Password, "", new { @class = "text-danger" })
@Html.TextBoxFor(x => x.ConfirmPassword, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.ConfirmPassword, "", new { @class = "text-danger" })
}
In this example, we have added the Compare data annotation to the ConfirmPassword property. The first argument of the Compare data annotation specifies the name of the property to compare against, which is the Password property in this case. The second argument is the error message that will be displayed if the properties do not match.
When the form is submitted, the framework will validate the model and check that the Password and ConfirmPassword properties match. If they do not match, the error message specified in the Compare data annotation will be displayed to the user.
In conclusion, data annotations in .NET MVC make it easy to enforce validation rules on data models. The Compare data annotation is just one of many available annotations, and it allows you to compare two properties in the model and ensure they match. This is a simple but effective way to ensure data accuracy and consistency in your application.