DataAnnotations - 禁止数字,或仅允许给定字符串

Ale*_*lex 17 c# validation asp.net-mvc data-annotations asp.net-mvc-2

是否可以使用ASP.NET MVC 2的DataAnnotations只允许字符(无数字),甚至提供允许字符串的白名单?例?

Mar*_*idd 36

使用RegularExpressionAttribute.

就像是

[RegularExpression("^[a-zA-Z ]*$")]
Run Code Online (Sandbox Code Playgroud)

将匹配az大小写和空格.

白名单看起来像

[RegularExpression("white|list")]
Run Code Online (Sandbox Code Playgroud)

这应该只允许"白色"和"列表"

[RegularExpression("^\D*$")]
Run Code Online (Sandbox Code Playgroud)

\ D表示非数字字符,因此上面应该允许包含0-9之外的任何字符串.

正则表达式很棘手,但在线有一些有用的测试工具,如:http: //gskinner.com/RegExr/


Ham*_*edH 5

您可以编写自己的验证器,其性能比正则表达式更好。

在这里,我为 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)}";
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

样品用途:

[WhiteList(2, 4, 5, 6)]
public int Number { get; set; }
Run Code Online (Sandbox Code Playgroud)