在进入数据库之前,我使用数据注释来验证模型。我有以下2个自定义属性:
[RequiredIf("OverseasResident", "Y")]
[PercentageRange]
public string Tax { get; set; }
仅当OverseasResident =“ Y”时才需要该属性,然后它检查该属性是否在PercentageRange中。否则,应忽略PercentageRange。
那么如果不需要,有什么方法可以忽略PercentageRange?
这是我的RequiredIfAttribute和PercentageRangeAttribute
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true)]
public class RequiredIfAttribute : ValidationAttribute
{
private readonly string _field;
private string _expectedValue;
public RequiredIfAttribute(string field, string expectedValue) : base("The {0} field is required if the {1} field equals {2}.")
{
_field = field;
_expectedValue = expectedValue;
}
public override object TypeId
{
get { return this; }
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var propertyName = validationContext.ObjectType.GetProperty(_field);
if (string.IsNullOrEmpty(_field) || propertyName == null) { return ValidationResult.Success; }
var error = new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
var propertyValue = Regex.Replace(propertyName.GetValue(validationContext.ObjectInstance, null).ToString().ToUpper(), @"\s+", "");
_expectedValue = Regex.Replace(_expectedValue.ToString().ToUpper(), @"\s+", "");
if (propertyValue == _expectedValue)
{
if (value == null || string.IsNullOrWhiteSpace(value.ToString())) { return error; }
return ValidationResult.Success;
}
var test = validationContext.GetType();
return ValidationResult.Success;
}
}
PercentageRangeAttribute:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class PercentageRangeAttribute : ValidationAttribute
{
public PercentageRangeAttribute() : base("The {0} field must be in percentage range.") { }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null || string.IsNullOrWhiteSpace(value.ToString())) { return ValidationResult.Success; }
bool fValid = false;
var inputValue = Regex.Replace(value.ToString(), @"\s+", "");
if (inputValue.IndexOf("%") == inputValue.Length - 1)
{
inputValue = inputValue.Replace("%", "");
}
var ok = decimal.TryParse(inputValue, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal parseValue);
fValid = ok && parseValue >= 0.0m && parseValue <= 100.0m;
if (fValid)
{
return ValidationResult.Success;
} else
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
}
}