2010-05-28 6 views

답변

27

RegularExpressionAttribute을 사용하십시오.

[RegularExpression("^[a-zA-Z ]*$")] 

뭔가 A-Z 대소 및 스페이스와 일치한다.

흰색 목록은 "화이트"와 위의 문자열을 허용해야하므로 D가 숫자가 아닌 문자를 나타냅니다

[RegularExpression("^\D*$")] 

\ "목록"허용해야

[RegularExpression("white|list")] 

과 같을 것 0-9 이외의 모든 것.

정규 표현식은 까다로운하지만 몇 가지 유용한 테스트 도구처럼 온라인이 있습니다 : http://gskinner.com/RegExr/

1

에 "[으로 RegularExpression]"

이 좋은 사이트를 사용합니다.

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.Linq; 

namespace Utils 
{ 
    /// <summary> 
    /// Define an attribute that validate a property againts a white list 
    /// Note that currently it only supports int type 
    /// </summary> 
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] 
    sealed public class WhiteListAttribute : ValidationAttribute 
    { 
     /// <summary> 
     /// The White List 
     /// </summary> 
     public IEnumerable<int> WhiteList 
     { 
      get; 
     } 

     /// <summary> 
     /// The only constructor 
     /// </summary> 
     /// <param name="whiteList"></param> 
     public WhiteListAttribute(params int[] whiteList) 
     { 
      WhiteList = new List<int>(whiteList); 
     } 

     /// <summary> 
     /// Validation occurs here 
     /// </summary> 
     /// <param name="value">Value to be validate</param> 
     /// <returns></returns> 
     public override bool IsValid(object value) 
     { 
      return WhiteList.Contains((int)value); 
     } 

     /// <summary> 
     /// Get the proper error message 
     /// </summary> 
     /// <param name="name">Name of the property that has error</param> 
     /// <returns></returns> 
     public override string FormatErrorMessage(string name) 
     { 
      return $"{name} must have one of these values: {String.Join(",", WhiteList)}"; 
     } 

    } 
} 

샘플 사용 :

[WhiteList(2, 4, 5, 6)] 
public int Number { get; set; } 
다음

나는 INT 속성에 대한 화이트리스트 검증을 썼다
관련 문제