laatzen/LaaProductionWeb/LaaProduction.Personalization/ComponentModel.DataAnnotations/DateTimeAttribute.cs
Stoyan Zlatev e32e553bfc clr types
2024-12-18 15:25:14 +01: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,
}
}