【问题标题】:Model Validation in asp.net Web API with dependent properties具有依赖属性的 asp.net Web API 中的模型验证
【发布时间】:2016-06-17 07:46:43
【问题描述】:

我正在使用模型验证来验证 Web api 请求:

动作过滤器属性

是否有可能对模型的属性“B”有一个验证规则,它依赖于属性“A”。考虑这个例子以获得更多说明

public class ValidationModel
{

    [Required]
    public int? Id { get; set; }

    public string Barcode { get; set; }

    public string BarcodeType { get; set; }
}

上述模型有一个 Id 属性是必需的,而 Barcode,BarcodeType 属性是可选的,是否可以将 BarcodeType 属性设置为必需当且仅当 Barcode 属性中有任何值(如果它不为 null 并且一个空字符串)

【问题讨论】:

标签: c# asp.net asp.net-web-api


【解决方案1】:

在 MVC 中有一个用于自定义验证的内置机制,它会为实现 IValidatableObject 的已发布 ViewModel 自动触发。

例如:

public class ValidationModel : IValidatableObject {
    // properties as defined above

     public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
         if (!string.IsNullOrWhiteSpace(Barcode) && string.IsNullOrWhiteSpace(BarcodeType)) {
             yield new ValidationResult("BarcodeType is required if Barcode is given", new[] { "BarcodeType" });
         }
     }
}

可以通过测试来检查控制器中验证是否成功 ModelState.IsValid

【讨论】:

  • yield new ValidationResult() 必须是 => yield return new ValidationResult(errorMessage: "", memberNames: new[] {""});
【解决方案2】:

我会检查 MVC 万无一失的验证。它是一个易于使用的包,将为您提供多种方式来完成基于条件的模型验证。它提供了许多验证器,例如:

  • [必要条件]

  • [需要的话]

  • [必需的IfTrue]

  • [RequiredIfFalse]

  • [RequiredIfEmpty]

  • [RequiredIfNotEmpty]

  • [RequiredIfRegExMatch]

  • [RequiredIfNotRegExMatch]

    它甚至可以与开箱即用的 jQuery 验证一起使用。 http://foolproof.codeplex.com/

【讨论】:

    猜你喜欢
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    相关资源
    最近更新 更多