ASP.NET Core Conditional Validation for controls [duplicate]

本小妞迷上赌 提交于 2020-02-23 02:51:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!