【问题标题】:ASP.NET MVC - Choose which validation annotations to useASP.NET MVC - 选择要使用的验证注解
【发布时间】:2013-04-04 12:44:03
【问题描述】:

我有一个具有如下属性的模型:

public class YourDetails {

  [Required(ErrorMessage = "Code is required")]
  [StringLength(10, ErrorMessage = "Code length is wrong", MinimumLength = 2)]
  [Range(0, int.MaxValue, ErrorMessage = "Please enter a value bigger than {1}")]
  public int Code { get; set; }

}

UI 验证是通过不显眼的 JS 验证插件以通常的开箱即用方式设置的。

问题:我有 2 个导航操作,返回和下一步。接下来很好,当事情出错时验证触发,当事情正确时,即.isValid()返回true,数据被传递到数据库服务等。

但是,当我按下“返回”时,我需要在保存之前以不同方式验证表单/ViewModel。 IE。确保 Code 是一个正整数,但不要打扰 RequiredStringLength 验证。

所以基本上我想在 Next 上完全验证,但在 Back 上部分验证。这可能吗?

【问题讨论】:

    标签: asp.net asp.net-mvc validation data-annotations


    【解决方案1】:

    当我过去做过类似的事情时,我发现最简单的方法是使用流畅的验证http://fluentvalidation.codeplex.com/wikipage?title=mvc。您可以将参数传递给验证器并切换到不同的规则集。

    【讨论】:

    • 我认为这是最好的方法。似乎使用 Fluent,您可以连接到客户端 JS 验证并选择何时验证什么。好的。谢谢。
    【解决方案2】:

    我过去曾使用过以下条件“必需”和“字符串长度”属性,它们运行良好。

    如果属性是必需的:

    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Reflection;
    
    namespace Website.Core.Mvc.DataAnnotations
    {
        [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
        public class RequiredIfAttribute : RequiredAttribute
        {
            public string OtherProperty { get; set; }
    
            public object OtherPropertyValue { get; set; }
    
            public RequiredIfAttribute(string otherProperty, object value)
                : base()
            {
                OtherProperty = otherProperty;
                OtherPropertyValue = value;
            }
    
            private object _TypeId = new object();
    
            public override object TypeId
            {
                get
                {
                    return _TypeId;
                }
            }
    
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                PropertyInfo property = validationContext.ObjectType.GetProperty(this.OtherProperty);
                if (property == null)
                {
                    return new ValidationResult(this.OtherProperty + " not found");
                }
    
                // Get 
                object actualOtherPropertyValue = property.GetValue(validationContext.ObjectInstance, null);
    
                // If the other property matches the expected value then validate as normal
                if (IsRequired(OtherPropertyValue, actualOtherPropertyValue))
                {
                    // Call base and validate required as normal
                    ValidationResult isValid = base.IsValid(value, validationContext);
                    return isValid;
                }
                return ValidationResult.Success;
            }
    
            protected virtual bool IsRequired(object otherPropertyValue, object actualOtherPropertyValue)
            {
                return object.Equals(OtherPropertyValue, actualOtherPropertyValue);
            }
        }
    }
    

    String Length If 属性:

    using System.ComponentModel.DataAnnotations;
    using System.Reflection;
    
    namespace Website.Core.Mvc.DataAnnotations
    {
        public class StringLengthIfAttribute : StringLengthAttribute
        {
            public string OtherProperty { get; set; }
    
            public object OtherPropertyValue { get; set; }
    
            public StringLengthIfAttribute(int maximumLength, string otherProperty, object value)
                : base(maximumLength)
            {
                OtherProperty = otherProperty;
                OtherPropertyValue = value;
            }
    
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                PropertyInfo property = validationContext.ObjectType.GetProperty(this.OtherProperty);
                if (property == null)
                {
                    return new ValidationResult(this.OtherProperty + " not found");
                }
    
                // Get 
                object actualOtherPropertyValue = property.GetValue(validationContext.ObjectInstance, null);
    
                // If the other property matches the expected value then validate as normal
                if (object.Equals(OtherPropertyValue, actualOtherPropertyValue))
                {
                    // Call base and validate required as normal
                    return base.IsValid(value, validationContext);
                }
                return null;
            }
        }
    }
    

    示例用法:

    public class MyModel
    {
        [RequiredIf("IsBack", false)]
        public string Name { get; set; }
    
        public bool IsBack { get; set; } 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-22
      • 2011-04-08
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 2011-12-21
      相关资源
      最近更新 更多