6

Let's say I have a following ViewModel :

    public class PersonViewModel
    {
        [Required]
        public String Email { get; set; }

        [Required]
        public String FirstName { get; set; }

        [Required]
        public String LastName { get; set; }
    }

This is a ViewModel not a original Entity, I use this model in two places, in the first one I want to validate all fields, but in another one I want to exclude Email field from model validation. Is there anyway to specify to exclude field(s) from validation?

Saber Amani
  • 6,409
  • 12
  • 53
  • 88

2 Answers2

12

You can use

ModelState.Remove("Email");

to remove entries in model state, that are related to hidden fields.

The best solution is to divide view model into two:

public class PersonViewModel
{
    [Required]
    public String FirstName { get; set; }

    [Required]
    public String LastName { get; set; }
}

public class PersonWithEmailViewModel : PersonViewModel
{
    [Required]
    public String Email { get; set; }
}
LukLed
  • 31,452
  • 17
  • 82
  • 107
  • Thanks for you reply, but what about using `[Bind(Exclude = "IsAdmin")]` ? – Saber Amani Apr 28 '13 at 19:45
  • 1
    @EAmani: Bind exludes from binding, not validation. If you don't want to have these problems, create dedicated view model. – LukLed Apr 28 '13 at 19:46
  • Great answer, I separated one class into two and made one a super class of the other, made my validation easier – mut tony Mar 08 '18 at 10:47
8

An ugly solution:

ModelState.Remove("Email");

Recommended solution:
Create another ViewModel. A VM is supposed to represent your view, so if your view has no Email field, make a suitable VM for it.

Artless
  • 4,522
  • 1
  • 25
  • 40