Hello,
I managed to register the date validator, which works, but I've noticed a problem/bug with the displayed validator text in the Draft (New version). When I enter dates that force the validator and then change the date for FieldToCompare, the "End Date cannot be earlier than the Start Date" text remains visible. I've noticed that the problem only appears when I press "Publish." When I first press "Save" and then "Publish," the validator works as expected.
public class LaterEndDateValidationRule : ValidationRule<DatesValidationRuleProperties, DateTime?>
{
public const string IDENTIFIER = "Xyz.DateLater";
public override async Task<ValidationResult> Validate(DateTime? value, IFormFieldValueProvider formFieldValueProvider)
{
string fieldToCompare = (Properties as DatesValidationRuleProperties)?.FieldToCompare;
if (!value.HasValue || string.IsNullOrWhiteSpace(fieldToCompare))
{
return ValidationResult.Success;
}
if (formFieldValueProvider.TryGet<object>(fieldToCompare, out var otherValueObj))
{
DateTime? otherValue = otherValueObj switch
{
DateTime dt => dt,
DateTimeOffset dto => dto.DateTime,
string s when DateTime.TryParse(s, out var parsed) => parsed,
_ => null
};
if (otherValue == null)
{
return new ValidationResult(false, $"Incorrect type of data entered in 'Field to compare'. '{fieldToCompare}' is not a Date type.");
}
if (otherValue.HasValue && otherValue.Value > value.Value)
{
return new ValidationResult(false, $"End Date cannot be earlier than the Start Date.");
}
return ValidationResult.Success;
}
else
{
return new ValidationResult(false, $"The given 'Field to compare' in Validation Rule does not exist in the given content type.");
}
}
}
public class DatesValidationRuleProperties : ValidationRuleProperties
{
[TextInputComponent(Label = "Field name from the current Content Item to compare.")]
public virtual string FieldToCompare { get; set; }
public override string GetDescriptionText(ILocalizationService localizationService)
=> $"Ensures the entered date is later than the date in field '{FieldToCompare}'.";
}
Did I miss something? There's no such problem when creating a new content item. Additionally, I can see that the new item form refreshes after pressing publish, which causes the validator text to disappear.
Environment
Xperience by Kentico version: [30.9.1]
.NET version: [8]