【问题标题】:RequiredIf Conditional Validation for two variables in MVC4RequiredIf 对 MVC4 中的两个变量进行条件验证
【发布时间】:2015-02-05 05:46:51
【问题描述】:

我有一个跟随的模型类

 public bool Saturday{ get; set; }

 public bool Sunday{ get; set; }

 public string Holiday{ get; set; }

我想在使用周六和周日字段的假日字段中使用RequiredIf 条件。我可以像下面这样使用吗

   [RequiredIf("Sunday,Saturday",false)]
   public string Holiday{ get; set; }

所以我不知道如何在我的模型类中使用RequiredIf条件,所以请有人帮助我

【问题讨论】:

  • 您可以在 MVC 中创建自己的自定义验证属性,此链接将帮助您创建它们codeproject.com/Articles/301022/…
  • 你指的是万无一失的RequiredIf属性吗? (如果有,添加标签)
  • 我添加了标签,但不起作用。你能给出使用万无一失的RequiredIf属性的任何示例代码吗? @斯蒂芬·穆克
  • 不,我的意思是问题底部的标签列表(如果您使用的是万无一失的)如果不是,那么您使用的是什么RequiredIf 属性?
  • 我不太清楚,因为我是 .Net Mvc 的初学者。而RequiredIfAttribute 类已经习惯了。而且通过使用 System.ComponentModel.DataAnnotations ,我已经完成了属性。如果您知道解决方案,请帮助我@Stephen Muecke

标签: c# asp.net-mvc-4 model required-field foolproof-validation


【解决方案1】:

也许在你的模型中试试这个:

[Required]
public bool Saturday{ get; set; }

[Required]
public bool Sunday{ get; set; }

[NotMapped]
public bool SatSun
{
    get
    {
        return (!this.Saturday && !this.Sunday);
    }
}

[RequiredIf("SatSun",true)]
public string Holiday{ get; set; }

【讨论】:

    【解决方案2】:

    如果需要更复杂的验证,我建议实施 IValidatableObject。

    public class YourModel : IValidatableObject
    {
        public bool Saturday{ get; set; }
    
        public bool Sunday{ get; set; }
    
        public string Holiday{ get; set; }
    
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var result = new List<ValidationResult>();
    
            if (Saturday == false && Sunday == false && string.IsNullOrEmpty(Holiday))
            {
                result.Add(new ValidationResult("Holiday is required outside weekends"));
            }
    
            return result;
        }
    }
    
    

    如果您将属性检查与 IValidatableObject 结合使用,请务必注意 this behaviour

    【讨论】:

      【解决方案3】:

      我的项目中有RequiredIf。

      [Required]
      public int SalesID { get; set; }
      
      [RequiredIf("SalesID==1", ErrorMessage = "License is required.")]
      public string License{ get; set; }
      

      它显示错误消息“需要许可证。”只有当 SalesID 为 1 时,License 才留空。如果 SalesID 为 1,License 不能为空。

      对于您的代码,它应该类似于

      [RequiredIf("Sunday,Saturday",AllowEmptyStrings=false)]
      public string Holiday{ get; set; }
      

      这意味着如果周日和周六为真,您可以允许 Holiday 属性为空字符串。

      【讨论】:

      • 它显示为“不包含带 1 个参数的构造函数”@Sukanya
      • AllowEmptyStrings 不被接受,即以下类型被接受但不起作用。 [RequiredIf("星期日、星期六",false)]
      • 给我一些关于错误的更多细节。请参阅RequiredIf 属性的重载。
      猜你喜欢
      • 2011-11-15
      • 1970-01-01
      • 2011-11-13
      • 2014-06-15
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多