2010-05-28 10 views

Odpowiedz

27

Użyj RegularExpressionAttribute.

Coś

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

pasowałby a-z dużych i małych liter i spacji.

Biała lista będzie wyglądać następująco

[RegularExpression("white|list")] 

co powinno pozwolić „białe” i „lista”

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

\ D reprezentuje znaki spoza numerycznych więc powyższe powinno pozwolić ciąg z tylko wszystko oprócz 0-9.

wyrażenia regularne są trudne, ale istnieje kilka przydatnych narzędzi do badania on-line takich jak: http://gskinner.com/RegExr/

1

Możesz napisać własny walidator, który ma lepszą wydajność niż wyrażenie regularne.

Tutaj napisałem białej listy walidator dla własności int:

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)}"; 
     } 

    } 
} 

próbki Zastosowanie:

[WhiteList(2, 4, 5, 6)] 
public int Number { get; set; } 
Powiązane problemy