2010-05-28 26 views

Trả lời

27

Sử dụng RegularExpressionAttribute.

Something như

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

sẽ phù hợp với một-z trên và chữ thường và không gian.

Một danh sách trắng sẽ giống như

[RegularExpression("white|list")] 

mà chỉ nên cho phép "trắng" và "danh sách"

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

\ D đại diện cho ký tự không phải là số nên ở trên nên cho phép một chuỗi với nhưng 0-9.

Biểu thức thông thường khó khăn nhưng có một số công cụ kiểm tra hữu ích trực tuyến như: http://gskinner.com/RegExr/

1

Bạn có thể viết validator của riêng bạn mà có hiệu suất tốt hơn so với một biểu thức chính quy.

Ở đây tôi đã viết một validator whitelist cho int tính:

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

    } 
} 

mẫu sử dụng:

[WhiteList(2, 4, 5, 6)] 
public int Number { get; set; } 
Các vấn đề liên quan