Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC must match validation attribute

I cant seem to find the annotation to use that makes sure 2 or more textboxes are the same.

For ex:

public class NewPasswordModel
{
    public string NewPassword { get; set; }

    [MustMatch(Name="NewPassword")] // What is the correct thing to come here.
    public string NewPasswordRep { get; set; }
}
like image 817
Shawn Mclean Avatar asked Mar 16 '11 19:03

Shawn Mclean


People also ask

How do you handle validation in MVC?

In code we need to check the IsValid property of the ModelState object. If there is a validation error in any of the input fields then the IsValid property is set to false. If all the fields are satisfied then the IsValid property is set to true. Depending upon the value of the property, we need to write the code.

How can we make a field mandatory in Cshtml?

cshtml. Add the "[Required]" attribute to the field that you want to make mandatory for insertion. The required attribute requires the "System. ComponentModel.

How do you validate model data using DataAnnotations attributes?

ComponentModel. DataAnnotations namespace includes the following validator attributes: Range – Enables you to validate whether the value of a property falls between a specified range of values. RegularExpression – Enables you to validate whether the value of a property matches a specified regular expression pattern.


2 Answers

You can use the native CompareAttribute

public class NewPasswordModel
{
    public string NewPassword { get; set; }

    [Compare("NewPassword")]
    public string NewPasswordRep { get; set; }
}
like image 148
Kim Tranjan Avatar answered Sep 17 '22 07:09

Kim Tranjan


You can install the DataAnnotationsExtensions.MVC3 nuget package, and use the EqualToAttribute.

public class NewPasswordModel
{
    public string NewPassword { get; set; }

    [EqualTo("NewPassword")]
    public string NewPasswordRep { get; set; }
}

It provides scripts for unobtrusive jQuery validation, so client-side validation will work as well.

like image 34
Bertrand Marron Avatar answered Sep 19 '22 07:09

Bertrand Marron