1

I have the following ViewModel:

public class RegistrationViewModel
{
    public Associate Associate { get; set; }

    public AssociateWeight AssociateWeight { get; set; }

    [DisplayName("Confirm Weight")]
    [Required(ErrorMessage = "Please enter a weight.")]
    [Compare("AssociateWeight.Weight", ErrorMessage = "Please enter identical weights.")]
    public decimal ConfirmWeight { get; set; }
}

The property AssociateWeight has a property called Weight that I would like to compare to ConfirmWeight to make sure they're equal. How can I accomplish this?

The Vanilla Thrilla
  • 1,915
  • 10
  • 30
  • 49
  • You'll need to write your own validator. That said, you can't do that with "only" Data-annotations (not unless you flatten down the AssociateWeight and then use the normal CompareAttribute) – João Silva May 06 '15 at 15:55
  • 1
    A view model is not a class for holding other models. It contains properties with you use in the view, so replace `public AssociateWeight AssociateWeight { get; set; }` with `public decimal Weight { get; set; }` (and include whatever other properties of `AssociateWeight` that you include in the view, then `[Compare("Weight", ...)]` will work as intended. Refer [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  May 06 '15 at 23:32

1 Answers1

0

You can achieve this by custom validation

Model

[RegistrationValidation]
public class RegistrationViewModel
{
    public Associate Associate { get; set; }
    public AssociateWeight AssociateWeight { get; set; }
    [DisplayName("Confirm Weight")]
    [Required(ErrorMessage = "Please enter a weight.")]   
    public decimal ConfirmWeight { get; set; }
}

Custom validation

public class RegistrationValidation : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        RegistrationViewModel app = value as RegistrationViewModel;
        if (app.AssociateWeight.weight != app.ConfirmWeight)
            {
                ErrorMessage = "Please enter identical weights.";
                return false;
            }
        return true;
    }
}
Golda
  • 3,823
  • 10
  • 34
  • 67