也许您可以使用自定义验证属性而不是使用 ValidateEntity?这是检查值是否为小数的自定义属性的示例:
public class MustBeDecimalAttribute : ValidationAttribute, IClientValidatable
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (Equals(value, null))
return ValidationResult.Success;
using (new CultureSubstitution(CultureInfo.InvariantCulture))
{
if (string.IsNullOrWhiteSpace(value.ToString()))
return ValidationResult.Success;
return !value.ToString().ToDecimal().HasValue
? new ValidationResult(FormatErrorMessage(validationContext.DisplayName))
: ValidationResult.Success;
}
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "mustbedecimal"
};
yield return rule;
}
但不要实现 IClientValidatable 因为您需要查询数据库。构建属性后,只需将其添加到模型中,如下所示:
[MustBeDecimal]
public decimal? RegularPrice { get; set; }