0

I am trying to add a custom model validation attribute to a date of birth field on my form. The attribute itself works as when I submit the form with an incorrect date it fails validation.

However I'm using jquery unobtrusive validation and while the standard model validation attributes are triggered and prevent form submission, this custom one doesn't.

My custom attribute is as follows:

public class DateMustBeInThePast : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if (value == null) return true;

        var date = (DateTime)value;
        return date < DateTime.Now;

    }
}

And I have applied this to my model field like this:

[Required(ErrorMessage = "Please enter a valid date")]
    [DisplayName("Date of Birth")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    [DateMustBeInThePast(ErrorMessage = "Date of Birth must be in the past")]
    public DateTime? Dob { get; set; }

So all the attributes such as the field is required and must be in the correct format work, but "DateMustBeInThePast" does not get checked until after the form has been submitted.

I have included the jquery.validate.js and jquery.validate.unobtrusive.js scripts in my view.

Can someone point me in the right direction for how to get the validation to check this rule?

James_P
  • 11
  • 2
  • You need to define your client-side custom adapter – freedomn-m Nov 12 '20 at 11:50
  • Does this answer your question? [Perform client side validation for custom attribute](https://stackoverflow.com/questions/4747184/perform-client-side-validation-for-custom-attribute) – freedomn-m Nov 12 '20 at 11:50

0 Answers0