Here I see two options:
1 - Code for an interface that will require you to create a ContactRequired class and a ContactOptional class based on ContactInterface. I believe this will allow you to have one StepModel where you must set the StepModel.Contact property to either the new ContactRequired () or the new ContactOption (). Then, when validaiton is executed for StepModel, it will be based on the class type set for the StepModel.Contact property.
public interface ContactInterface { string Title { get; set; } string FirstName { get; set; } string LastName { get; set; } string Email { get; set; } string Phone { get; set; } } public class ContactOptional : ContactInterface { public string Title { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Phone { get; set; } } public class ContactRequired : ContactInterface { public string Title { get; set; } public string FirstName { get; set; } [Required(ErrorMessage = "Please enter LastName")] public string LastName { get; set; } [Required(ErrorMessage = "Please enter Email")] public string Email { get; set; } public string Phone { get; set; } } public class StepModel { public ContactInterface Contact { get; set; } }
Using:
StepModel smTest = new StepModel(); ContactRequired crContact = new ContactRequired(); ContactOptional coContact = new ContactOptional(); List<ValidationResult> lErrors = new List<ValidationResult>(); smTest.Contact = coContact; //Validate Option if (Validator.TryValidateObject(smTest, new ValidationContext(smTest, serviceProvider: null, items: null), lErrors, true)) { //Code should reach this as the model should be valid; } smTest.Contact = crContact; //Validate Required if (Validator.TryValidateObject(smTest, new ValidationContext(smTest, serviceProvider: null, items: null), lErrors, true)) { //Code should not reach this as the model should be invalid; }
2. Create a custom required attribute that will look for another property of the Contact model (for example, bool UseValidation) to determine whether the required check should be performed or if it should simply return true to the default value. I initially do not provide code for this parameter, since for each type of validation attribute in your class you will need a custom attribute. Also, I think option 1 is best if you have no specific reason.
source share