问题
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?
回答1:
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;
}
}
来源:https://stackoverflow.com/questions/58744905/asp-net-core-conditional-validation-for-controls