有没有可能使用ASP.NET MVC2的DataAnnotations只允许字符(没有数字),或者甚至提供允许字符串的白名单?例如?
发布于 2017-03-30 22:03:24
您可以编写自己的验证器,它的性能比正则表达式更好。
这里我为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)}";
}
}
}示例用法:
[WhiteList(2, 4, 5, 6)]
public int Number { get; set; }https://stackoverflow.com/questions/2932053
复制相似问题