laatzen/LaaProductionWeb/LaaProduction.Personalization/ComponentModel.DataAnnotations/DateTimeAttribute.cs

76 lines
2.7 KiB
C#
Raw Normal View History

2023-08-16 14:11:41 +00:00
namespace LaaProduction.Personalization.ComponentModel.DataAnnotations
{
using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
public class DateTimeAttribute : ValidationAttribute
{
private readonly DateTimeOptions option;
2024-12-18 14:25:14 +00:00
private readonly string otherProperty;
2023-08-16 14:11:41 +00:00
2024-12-18 14:25:14 +00:00
public DateTimeAttribute(DateTimeOptions option, string otherProperty)
2023-08-16 14:11:41 +00:00
{
this.option = option;
this.otherProperty = $"{otherProperty}";
}
2024-12-18 14:25:14 +00:00
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
2023-08-16 14:11:41 +00:00
{
2024-12-18 14:25:14 +00:00
var validationMessage = default(string);
2023-08-16 14:11:41 +00:00
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.";
}
2024-12-18 14:25:14 +00:00
if (string.IsNullOrWhiteSpace(validationMessage))
2023-08-16 14:11:41 +00:00
{
return ValidationResult.Success;
}
return new ValidationResult(validationMessage);
}
}
public enum DateTimeOptions
{
GreaterThan,
SmallerThan,
}
}