2017-10-16 2 views
1

내가 가진 것을 감안할 때?StringLengthAttribute로 속성을 프로그래밍 방식으로 테스트하여 유효한지 확인할 수 있습니까?</p> <pre><code>[StringLength(10)] public string Bibble {get; set;} </code></pre> <p>나는 개별적으로 Bibble가 유효한지 확인할 수 있습니다 :

PropertyInfo[] props = typeof(MyBibbleObject).GetProperties(); 
foreach (PropertyInfo prop in props) 
{ 
    object[] attrs = prop.GetCustomAttributes(true); 
    foreach (object attr in attrs) 
    { 
     StringLengthAttribute stringLengthAttribute = attr as StringLengthAttribute; 
     if (stringLengthAttribute != null) 
     { 
      string propName = prop.Name; 

// Could be IsValid? 
      stringLengthAttribute.IsValid() 


     } 
    } 
} 

을하지만 IsValid 방법은 내가 기대되지 않은 객체를 필요

나는 생각했다. 그것이 유효한지 아닌지를 결정하는 더 좋은 방법이 있는지 궁금합니다. 나는 재산마다 그것을해야한다.

+0

올바른지, 테스트하려는 값을 전달합니다. – Igor

+0

현재 상황에서 ModelState에 액세스 할 수 없습니까? – GGO

+0

나는 a) 값이 필요하고 b) 정상적인 속성처럼 속성 자체의 메타 데이터에 액세스 할 수 없을 때 배열 및 다양한 데이터 유형에 대해 작업 할 수 있는지 여부를 고려했습니다. – NibblyPig

답변

2

내장 된 Validator 클래스를 사용할 수 있습니다. 그 사용법은 다소 모호하지만 그래도 여전히 :

// instance is your MyBibbleObject object 
var ctx = new ValidationContext(instance); 
// property to validate 
ctx.MemberName = "Bibble"; 
// this will store results of validation. If empty - all fine 
var results = new List<ValidationResult>(); 
// pass value to validate (it won't take it from your object) 
Validator.TryValidateProperty(instance.Bibble, ctx, results); 
관련 문제

 관련 문제