使用 asp.net mvc 使某个枚举值的验证失败
Make validation fail for a certain enum value with asp.net mvc
是否存在验证某个枚举值的枚举验证属性?
或者我应该手动执行此操作:
if(viewModel.State == State.None) base.AddModelError("","wrong enum selected...");
你会怎么做?
我会创建自己的验证属性,例如(未测试):
public enum SomeEnum
{
Right,
Wrong
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class EnumValueAttribute : ValidationAttribute
{
private const string DefaultErrorMessage = "Cannot be that value";
public SomeEnum EnumVal { get; private set; }
public EnumValueAttribute(SomeEnum enumVal)
: base(DefaultErrorMessage)
{
EnumVal = enumVal;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, EnumVal);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var enumVal = (SomeEnum) Enum.Parse(typeof (SomeEnum), value.ToString());
if (enumVal != EnumVal)
{
return new ValidationResult(DefaultErrorMessage);
}
return ValidationResult.Success;
}
}
用法:
public class TestModel
{
[EnumValue(SomeEnum.Right)]
public SomeEnum Value { get; set; }
}
已更新
所以这是您可以合理理解的通用代码,我没有测试过这段代码,但它确实可以编译。请注意,我已经为枚举分配了数字值。
public enum SomeEnum
{
Right = 1,
Wrong = 2,
Other = 3
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class DisallowEnumValueAttribute : ValidationAttribute
{
public object DissallowedEnum { get; private set; }
public Type EnumType { get; private set; }
public DisallowEnumValueAttribute(Type enumType, object dissallowedEnum)
{
if (!enumType.IsEnum)
throw new ArgumentException("Type must be an enum", "enumType");
DissallowedEnum = dissallowedEnum;
EnumType = enumType;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var disallowed = Convert.ChangeType(DissallowedEnum, EnumType);
var enumVal = Convert.ChangeType(value, EnumType);
if (disallowed == null || enumVal == null)
throw new Exception("Something is wrong"); //or return validation result
if (enumVal == disallowed)
{
return new ValidationResult("This value is not allowed");
}
return ValidationResult.Success;
}
}
public class TestModel
{
[DisallowEnumValue(typeof(SomeEnum), SomeEnum.Wrong)]
public SomeEnum Thing { get; set; }
}
枚举:
public enum SomeEnum
{
Right = 1,
Wrong = 2,
Other = 3
}
视图模型:
public class TestModel
{
[Range((int)(SomeEnum.Right), (int)(SomeEnum.Right), ErrorMessage = "Please select an Enum value")]
public SomeEnum Value { get; set; }
}
不需要其他代码。枚举基本上是整数,因此您可以使用 Range 属性来验证它们。
我的枚举验证是这样的,并且适用于数据注释验证
public enum CreatedBySelfOrOthersEnumValues
{
Self,
Others
}
public class CampaignRegisterValidationModel
{
[Required]
public string Name { get; set; }
[Required]
public CreatedBySelfOrOthersEnumValues CreatedForSelfOrOthers { get; set; }
[Required]
public int CountryCode { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
然后验证它
if (ModelState.IsValid)
{
}
是否存在验证某个枚举值的枚举验证属性?
或者我应该手动执行此操作:
if(viewModel.State == State.None) base.AddModelError("","wrong enum selected...");
你会怎么做?
我会创建自己的验证属性,例如(未测试):
public enum SomeEnum
{
Right,
Wrong
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class EnumValueAttribute : ValidationAttribute
{
private const string DefaultErrorMessage = "Cannot be that value";
public SomeEnum EnumVal { get; private set; }
public EnumValueAttribute(SomeEnum enumVal)
: base(DefaultErrorMessage)
{
EnumVal = enumVal;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, EnumVal);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var enumVal = (SomeEnum) Enum.Parse(typeof (SomeEnum), value.ToString());
if (enumVal != EnumVal)
{
return new ValidationResult(DefaultErrorMessage);
}
return ValidationResult.Success;
}
}
用法:
public class TestModel
{
[EnumValue(SomeEnum.Right)]
public SomeEnum Value { get; set; }
}
已更新
所以这是您可以合理理解的通用代码,我没有测试过这段代码,但它确实可以编译。请注意,我已经为枚举分配了数字值。
public enum SomeEnum
{
Right = 1,
Wrong = 2,
Other = 3
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class DisallowEnumValueAttribute : ValidationAttribute
{
public object DissallowedEnum { get; private set; }
public Type EnumType { get; private set; }
public DisallowEnumValueAttribute(Type enumType, object dissallowedEnum)
{
if (!enumType.IsEnum)
throw new ArgumentException("Type must be an enum", "enumType");
DissallowedEnum = dissallowedEnum;
EnumType = enumType;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var disallowed = Convert.ChangeType(DissallowedEnum, EnumType);
var enumVal = Convert.ChangeType(value, EnumType);
if (disallowed == null || enumVal == null)
throw new Exception("Something is wrong"); //or return validation result
if (enumVal == disallowed)
{
return new ValidationResult("This value is not allowed");
}
return ValidationResult.Success;
}
}
public class TestModel
{
[DisallowEnumValue(typeof(SomeEnum), SomeEnum.Wrong)]
public SomeEnum Thing { get; set; }
}
枚举:
public enum SomeEnum
{
Right = 1,
Wrong = 2,
Other = 3
}
视图模型:
public class TestModel
{
[Range((int)(SomeEnum.Right), (int)(SomeEnum.Right), ErrorMessage = "Please select an Enum value")]
public SomeEnum Value { get; set; }
}
不需要其他代码。枚举基本上是整数,因此您可以使用 Range 属性来验证它们。
我的枚举验证是这样的,并且适用于数据注释验证
public enum CreatedBySelfOrOthersEnumValues
{
Self,
Others
}
public class CampaignRegisterValidationModel
{
[Required]
public string Name { get; set; }
[Required]
public CreatedBySelfOrOthersEnumValues CreatedForSelfOrOthers { get; set; }
[Required]
public int CountryCode { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
然后验证它
if (ModelState.IsValid)
{
}