首页 文章

如果字段为空,如何忽略验证注释?

提问于
浏览
0

我有这些课程:

Class Parent
{
   [Required]
   String Name ;

   Child child ;
}

Class Child
{
   [Required]
   Child FirstName ;
   [Required]
   Child LastName ;
}

我有一个表单显示父实体字段,包括Childs . 使用我的配置,子项的FistName和LastName是必需的,如果留空,则验证失败 .

如果孩子的FirstName和LastName都被提交为空白,我需要的是验证通过 . 如果提交了FirstName或LastName,则另一个是必需的,验证应该失败 .

我怎样才能做到这一点?

2 回答

  • 2

    只需将注释更改为:

    [必需(AllowEmptyString =真)]

    这将允许空字符串通过验证 . 如果需要,您可以在服务器上执行其他验证 .

    此链接应该有所帮助:

    RequiredAttribute.AllowEmptyStrings Property

  • 2

    我会在模型上实现自己的验证方法 . 你的模型最终会看起来像这样:

    public class Child : IValidatableObject {
       public string FirstName {get; set;}
       public string LastName {get; set;}
    
       public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
           if ((string.IsNullOrEmpty(this.FirstName) && !string.IsNullOrEmpty(this.LastName)) || (!string.IsNullOrEmpty(this.FirstName) && string.IsNullOrEmpty(this.LastName))) {
               yield return new ValidationResult("You must supply both first name and last name or neither of them");
           }
       }
    }
    

相关问题