Skip to content

Instantly share code, notes, and snippets.

@Vovanda
Last active March 31, 2021 18:09
Show Gist options
  • Save Vovanda/c4265f3308649b43104707118c46e892 to your computer and use it in GitHub Desktop.
Save Vovanda/c4265f3308649b43104707118c46e892 to your computer and use it in GitHub Desktop.
Реализация CompareTo в качестве атрибута валидации
using System;
using System.ComponentModel.DataAnnotations;
namespace ComponentModel.DataAnnotations
{
/// <summary>
/// Реализация CompareTo в качестве атрибута валидации.
/// </summary>
public class CompareToAttribute : ValidationAttribute
{
public CompareToAttribute(string otherProperty, Comparison comparison)
{
_otherProperty = otherProperty;
_comparison = comparison;
}
public override bool RequiresValidationContext => true;
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var errorMessage = $"Unknown property: { _otherProperty}";
var propertyInfo = validationContext.ObjectType.GetProperty(_otherProperty);
if (propertyInfo != null)
{
var otherValue = propertyInfo.GetValue(validationContext.ObjectInstance, null);
Comparison comparison;
if (value != null)
{
var diff = ((IComparable)value).CompareTo(otherValue);
if (diff < 0) comparison = Comparison.Less;
else if (diff == 0) comparison = Comparison.Equal;
else comparison = Comparison.Greater;
}
else
{
comparison = otherValue == null ? Comparison.Equal : Comparison.Less;
}
if ((_comparison & comparison) == comparison) return null;
errorMessage = ErrorMessage;
}
return new ValidationResult(errorMessage);
}
private readonly string _otherProperty;
private readonly Comparison _comparison;
}
[Flags]
public enum Comparison
{
Less = 1, Equal = 2, Greater = 4,
NotEqual = Less | Greater,
LessOrEqual = Less | Equal,
GreaterOrEqual = Greater | Equal
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment