Reputation: 11
Apologies if this is a dumb question - I'm new to Razor pages and ASP.Net Core.
I have a page set up with data binding and various attributes defined on the model to provide some basic client side validation and they work fine, however I have a date field that I need to ensure isn't being set to a future date.
I know how to validate that a date is in the past - that's not the problem - but I want to be able to validate the date and display the error message in a span beneath the field just like I would if a required field is missing, wrong length etc.
I assumed I could add some attributes to the property on the model along the lines of
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}, ApplyFormatInEditMode = true)")]
[Range(typeof(DateTime), "01/01/1980", DateTime.Today.ToString(), ErrorMessage = "Value must be in the past")]
public DateTime Date { get; set; }
But I get an error to the effect that I can only use constants (I had feared this was the case).
Next I looked at whether I can invalidate that field in code but I can't see how you would do it and I've not been able to find a comparable example anywhere. I would like to think that I can add an error into the ModelState for the page but I can't see how.
As I say I can think of lots of other ways of doing the validation but I'd like for consistency for the validation errors to be presented in the same way as other attribute driven validation.
Any help gratefully received.
Upvotes: 0
Views: 1388
Reputation: 11
OK... found (a) solution...
I've created a custom validation method
public class CustomValidationMethods
{
public static ValidationResult PastDate(DateTime date)
{
return DateTime.Compare(date, DateTime.Today) > 0 ? new ValidationResult("Date cannot be in the future") : ValidationResult.Success;
}
}
and added this in the model definition
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
[CustomValidation(typeof(CustomValidationMethods), nameof(CustomValidationMethods.PastDate))]
public DateTime Date { get; set; }
I don't know if this is the best answer but it works and it makes sense to me.
Upvotes: 1