2013-05-07 48 views
0

是否可以使用ASP MVC的DataAnnotation来要求字符串为两种长度之一?这个例子显然是行不通的,但我沿着这些线路验证字符串是两种长度之一

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

回答

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 
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中

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomStringLengthAttribute), typeof(StringLengthAttributeAdapter)); 
的Appplication_start注册适配器