How I can skip all the validation of a model base on one of its property. For instance, if the WillBeDeleted
property of the object is true the validator skips all the validation rules.
namespace ViewModel
{
public class ContactForm : IViewModel
{
[ValidateNever]
public Contact Item { get; set; }
public Category Category { get; set; }
[Required, DisplayName("First name")]
[StringLength(200, ErrorMessage = "First name should not exceed 200 characters.")]
public string FirstName { get; set; }
[Required, DisplayName("Last name")]
[StringLength(200, ErrorMessage = "Last name should not exceed 200 characters.")]
public string LastName { get; set; }
public List<TelephonesSubForm> Telephones { get; set; } = new List<TelephonesSubForm>();
public List<EmailsSubForm> Emails { get; set; } = new List<EmailsSubForm>();
public class TelephonesSubForm : IViewModel
{
public int Id { get; set; }
public bool MustBeDeleted { get; set; }
[Required]
public TelephoneAndEmailType Type { get; set; }
[Required]
[StringLength(200, MinimumLength = 10, ErrorMessage = "Telephone should not exceed 200 characters.")]
public string Telephone { get; set; }
}
public class EmailsSubForm
{
public int Id { get; set; }
public bool MustBeDeleted { get; set; }
[Required]
public TelephoneAndEmailType Type { get; set; }
[Required]
[StringLength(200, MinimumLength = 10, ErrorMessage = "Email should not exceed 200 characters.")]
public string Email { get; set; }
}
}
}
In the given sample model, when the MustBeDeleted
is true
it means that the item of email or telephone will be deleted on the save action.
I have searched and found that several questions about conditional (custom) validation and they are suggesting to remove the specific keys from the ModelState
before checking the validation state of it. Like this one.