laatzen/LaaProductionWeb/LaaProduction.Personalization/ComponentModel.DataAnnotations/DateTimeAttribute.cs
2024-07-17 13:13:41 +02:00

76 lines
2.7 KiB
C#

namespace LaaProduction.Personalization.ComponentModel.DataAnnotations
{
using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
public class DateTimeAttribute : ValidationAttribute
{
private readonly DateTimeOptions option;
private readonly String otherProperty;
public DateTimeAttribute(DateTimeOptions option, String otherProperty)
{
this.option = option;
this.otherProperty = $"{otherProperty}";
}
protected override ValidationResult IsValid(Object value, ValidationContext validationContext)
{
var validationMessage = default(String);
if (value is DateTime currentDate)
{
var property = validationContext
?.ObjectType
?.GetProperty(this.otherProperty, BindingFlags.Public | BindingFlags.Instance);
if (property is null)
{
validationMessage = $"The '{this.otherProperty}' is invalid.";
}
else
{
var otherValue = property
.GetValue(validationContext?.ObjectInstance);
var otherDisplayName = property
.GetCustomAttribute<DisplayAttribute>()
?.GetName() ?? this.otherProperty;
if (otherValue is DateTime otherDate)
{
if (this.option == DateTimeOptions.GreaterThan && currentDate <= otherDate)
{
validationMessage = $"The '{validationContext.DisplayName}' should be greater than '{otherDisplayName}'";
}
else if (this.option == DateTimeOptions.SmallerThan && currentDate >= otherDate)
{
validationMessage = $"The '{validationContext.DisplayName}' should be smaller than '{otherDisplayName}'";
}
}
else
{
validationMessage = $"The '{otherDisplayName}' is invalid.";
}
}
}
else
{
validationMessage = $"The '{validationContext?.DisplayName}' is invalid.";
}
if (String.IsNullOrWhiteSpace(validationMessage))
{
return ValidationResult.Success;
}
return new ValidationResult(validationMessage);
}
}
public enum DateTimeOptions
{
GreaterThan,
SmallerThan,
}
}