【问题标题】:How to validate model depends on bool datatype value using asp.net core web api如何验证模型取决于使用 asp.net core web api 的 bool 数据类型值
【发布时间】:2017-04-11 03:17:56
【问题描述】:

我使用 asp.net core web API 创建了一个模型,我必须验证属性取决于 bool 数据类型属性值。

如果 IsWaitingList 属性为 true ,则 WaitingListEncounterOrOtherEncounter 属性为必填属性,否则不是必填字段。

public class CenterConfiguration
    {
        public Guid Id { get; set; } = Guid.NewGuid();
        public bool? IsWaitingList { get; set; }
        [Required(ErrorMessage = "Please enter waiting list encounter or other encounter")]
        public int WaitingListEncounterOrOtherEncounter { get; set; }
    } 

如果有人知道,请告诉我。

【问题讨论】:

    标签: c# asp.net-mvc-4 asp.net-web-api2 asp.net-core-webapi


    【解决方案1】:

    您可以实现IValidatableObject 来检查复杂的验证条件。

    public class CenterConfiguration : IValidatableObject {
        public Guid Id { get; set; } = Guid.NewGuid();
        public bool? IsWaitingList { get; set; }
        public int? WaitingListEncounterOrOtherEncounter { get; set; }
    
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
             if (IsWaitingList && !WaitingListEncounterOrOtherEncounter.HasValue) {
                 yield return new ValidationResult(
                     "Please enter waiting list encounter or other encounter",
                     new[] { "WaitingListEncounterOrOtherEncounter" }
                 );
             }
        }
    }
    

    还请注意,我将 WaitingListEncounterOrOtherEncounterint 更改为 int?,因此您实际上可以将此值留空。

    另见How do I use IValidatableObject?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-26
      • 2018-08-24
      • 1970-01-01
      • 2023-03-23
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多