Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude Fields From Model Validation

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?

like image 728
saber Avatar asked Apr 28 '13 19:04

saber


Video Answer


1 Answers

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; }
}
like image 187
LukLed Avatar answered Sep 30 '22 07:09

LukLed