如果字段为空,如何忽略验证注释? [英] How to ignore validation annotation if field is blank?

查看:132
本文介绍了如果字段为空,如何忽略验证注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

Class Parent
{
   [Required]
   String Name ;

   Child child ;
}

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

我有一个显示父级实体字段(包括孩子的字段)的表格。在我的配置中,孩子的FistName和LastName是必需的,如果留为空白,则会导致验证失败。

I have a form showing the Parent entity fields including the Childs's. With my configuration the child's FistName and LastName are required and if left blank causes validation to fail.

如果孩子的名字和姓氏都被提交为空白,我需要通过验证。如果提交了名字或姓氏,则另一个是必需的,并且验证将失败。

What I need is have validation pass if both the child's FirstName and LastName are submitted blank. If either FirstName or LastName is submitted then the other is required and validation should fail.

如何实现?

推荐答案

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

I would implement your own validation method on the model. Your model would end up looking something like this:

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");
       }
   }
}

这篇关于如果字段为空,如何忽略验证注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆