2010-05-28 14 views

Respuesta

27

Utilice RegularExpressionAttribute.

Algo así como

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

igualaría a-z mayúsculas y minúsculas y espacios.

Una lista blanca sería algo como

[RegularExpression("white|list")] 

que sólo debe permitir que "blanco" y "lista"

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

\ D representa caracteres no numéricos por lo que lo anterior debe permitir que una cadena con cualquier cosa menos 0-9.

Las expresiones regulares son difíciles pero hay algunas herramientas de prueba de votos en línea como: http://gskinner.com/RegExr/

1

Usted puede escribir su propio validador que tiene un mejor rendimiento que una expresión regular.

Aquí me escribió un validador lista blanca para las propiedades 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)}"; 
     } 

    } 
} 

la muestra Uso:

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