自定义了一个验证特性,要求值为指定的几个值之一
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public class EnumerationAttribute : ValidationAttribute
{
///
/// 错误消息格式
///
private readonly string _errorMessageStr = "{0} 字段必须在[{1}]之中。";
///
/// 枚举值
///
protected string[] Values { get; set; }
///
/// 构造函数
///
///
public EnumerationAttribute(params string[] values)
{
Values = values;
}
public override string FormatErrorMessage(string name)
{
return string.Format(CultureInfo.CurrentCulture, _errorMessageStr, name, string.Join(",", Values));
}
public override bool IsValid(object value)
{
var valueStr = value as string;
if (valueStr == null)
{
return true;
}
return Values.Contains(valueStr);
}
}
使用如下
[Required]
[Enumeration("1", "3")]
[Display(Name = "客户类型")]
public string CompanyClass { get; set; }
表示客户类型只能是1或者3,但是传入2也验证通过了。验证方式如下
var results = new List();
var context = new ValidationContext(model); //model的客户类型为2
Validator.TryValidateObject(model, context, results);
调试发现results 为空,这是为什么
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public class EnumerationAttribute : ValidationAttribute
{
///
/// 错误消息格式
///
private readonly string _errorMessageStr = "{0} 字段必须在[{1}]之中。";
///
/// 枚举值
///
protected string[] Values { get; set; }
///
/// 构造函数
///
///
public EnumerationAttribute(params string[] values)
{
Values = values;
}
public override string FormatErrorMessage(string name)
{
return string.Format(CultureInfo.CurrentCulture, _errorMessageStr, name, string.Join(",", Values));
}
public override bool IsValid(object value)
{
var valueStr = value as string;
if (valueStr == null)
{
return true;
}
return Values.Contains(valueStr);
}
}
使用如下
[Required]
[Enumeration("1", "3")]
[Display(Name = "客户类型")]
public string CompanyClass { get; set; }
表示客户类型只能是1或者3,但是传入2也验证通过了。验证方式如下
var results = new List();
var context = new ValidationContext(model); //model的客户类型为2
Validator.TryValidateObject(model, context, results);
调试发现results 为空,这是为什么