0

是否可以使用 ASP MVCDataAnnotation要求字符串为两种长度之一?这个例子显然不起作用,但我正在考虑这些方面的东西

    [Required]
    [DisplayName("Agent ID")]
    [StringLength(8) || StringLength(10)]
    public string AgentId
4

2 回答 2

3

您可以编写自己的验证属性来处理它:

public class UserStringLengthAttribute : ValidationAttribute
    {
        private int _lenght1;
        private int _lenght2;


        public UserStringLengthAttribute(int lenght2, int lenght1)
        {
            _lenght2 = lenght2;
            _lenght1 = lenght1;
        }

        public override bool IsValid(object value)
        {
            var typedvalue = (string) value;
            if (typedvalue.Length != _lenght1 || typedvalue.Length != _lenght2)
            {
                ErrorMessage = string.Format("Length should be {0} or {1}", _lenght1, _lenght2);
                return false;
            }
            return true;
        }
    }

并使用它:

[Required]
[DisplayName("Agent ID")]
[UserStringLength(8,10)]
public string AgentId
于 2013-05-07T16:09:25.047 回答
0

是的,你可以这么做 。做一个继承自 StringLength 的自定义验证器,这将适用于客户端和服务器端

public class CustomStringLengthAttribute : StringLengthAttribute
    {
        private readonly int _firstLength;
        private readonly int _secondLength;


        public CustomStringLengthAttribute(int firstLength, int secondLength)
            : base(firstLength)
        {
            _firstLength = firstLength;
            _secondLength = secondLength;

        }

        public override bool IsValid(object value)
        {

            int valueTobeValidate = value.ToString().Length;

            if (valueTobeValidate == _firstLength)
            {
                return base.IsValid(value);
            }

            if (valueTobeValidate == _secondLength)
            {
                return true;
            }
            return base.IsValid(value);

        }
    }

并在 Global.asax.cs 的 Appplication_start 中注册适配器

 DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomStringLengthAttribute), typeof(StringLengthAttributeAdapter));
于 2013-05-07T16:29:55.180 回答