2

For example, I have these 3 properties in my view model

public class PageViewModel
{
            [Required]
            public bool? HasControl { get; set; }
            [Required] 
            public bool? Critical { get; set; }
            [Required]         
            public string Description { get; set; }
}

The problem here is that I want to make the properties

Critical 
Description

required if HasControl is true or not required if it's false, which is a radio button control.

I have tried disabling the controls on client-side but they still fail when checking Modelstate.IsValid.

Is there a way to handle this situation?

Arjun Vachhani
  • 1,761
  • 3
  • 21
  • 44
Jackal
  • 3,359
  • 4
  • 33
  • 78

1 Answers1

3

You need to implement IValidatableObject. Put validation checks in Validate method. return list of errors in the end.

public class PageViewModel : IValidatableObject
{
    public bool? HasControl { get; set; }
    public bool? Critical { get; set; }
    public string Description { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        List<ValidationResult> errors = new List<ValidationResult>();
        if (HasControl == true)
        {
            if (Critical == null)
                errors.Add(new ValidationResult($"{nameof(Critical)} is Required.", new List<string> { nameof(Critical) }));

            if (string.IsNullOrWhiteSpace(Description))
                errors.Add(new ValidationResult($"{nameof(Description)} is Required.", new List<string> { nameof(Description) }));
        }
        return errors;
    }
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Arjun Vachhani
  • 1,761
  • 3
  • 21
  • 44