Игнорировать другие проверки, если они действительны. Аннотации данных C # - PullRequest
0 голосов
/ 04 октября 2018

Я использую аннотации данных для проверки моделей до поступления в базу данных.У меня есть 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));
        }
    }
}
...