首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >DataAnnotations -不允许数字,或仅允许给定的字符串

DataAnnotations -不允许数字,或仅允许给定的字符串
EN

Stack Overflow用户
提问于 2010-05-29 03:54:52
回答 3查看 20.1K关注 0票数 19

有没有可能使用ASP.NET MVC2的DataAnnotations只允许字符(没有数字),或者甚至提供允许字符串的白名单?例如?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-05-29 04:01:38

使用RegularExpressionAttribute

就像这样

代码语言:javascript
运行
复制
[RegularExpression("^[a-zA-Z ]*$")]

将匹配a-z大小写和空格。

白名单看起来像这样

代码语言:javascript
运行
复制
[RegularExpression("white|list")]

它应该只允许“白色”和“列表”

代码语言:javascript
运行
复制
[RegularExpression("^\D*$")]

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

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

票数 42
EN

Stack Overflow用户

发布于 2017-03-30 22:03:24

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

这里我为int属性编写了一个白名单验证器:

代码语言:javascript
运行
复制
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)}";
        }

    }
}

示例用法:

代码语言:javascript
运行
复制
[WhiteList(2, 4, 5, 6)]
public int Number { get; set; }
票数 5
EN

Stack Overflow用户

发布于 2010-05-29 04:24:38

是。使用“RegularExpression”

这是一个关于正则表达式http://www.regexlib.com/CheatSheet.aspx的很好的站点

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2932053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档