将字符串验证为两个长度之一

时间:2013-05-07 16:02:28

标签: asp.net-mvc asp.net-mvc-3 validation asp.net-mvc-4 model

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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));