0

I created custom validation in MVC model to check whether EndDate field is greater than StartDate. Like this:

public class ViewModel: IValidatableObject
{
    [Required]
    public DateTime StartDate { get; set; }
    [Required]    
    public DateTime EndDate { get; set; } 

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
       if (EndDate < StartDate)
       {
           yield return 
             new ValidationResult(errorMessage: "EndDate must be greater than StartDate",
                                  memberNames: new[] { "EndDate" });
       }
    }
}

thanks to this post for showing me how do that.

But this code works in Server side only. It doesn't validates before submitting the form. Means it doesn't show any error message when i put

@Html.ValidationMessageFor(x => x.EndDate)

Can any one help me to make this validation possible in the client side using jquery unobtrusive validation?

Community
  • 1
  • 1
Anil P Babu
  • 1,235
  • 3
  • 26
  • 47
  • 1
    You need to create a class that inherits `ValidationAttribute` and implements `IClientValidatable` - [The Complete Guide To Validation In ASP.NET MVC 3 - Part 2](http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2) –  Oct 05 '16 at 07:16
  • 1
    it wont show cause you havent defined the jquery method , try adding a jquery method that matches your needs https://jqueryvalidation.org/jQuery.validator.addMethod/ or create a custom validation method using js – hdrdiab Oct 05 '16 at 08:59
  • @hdriab that's bad practice right? cause you are duplicating the code for same functionality twice - one at model and one at view. I am trying to hold all my business logic with in my model. That's the essence of MVC after all. – Anil P Babu Oct 05 '16 at 10:50
  • 1
    You have to write javascript code for the client side validation. Your browser does not know anything about c# code on the server - it only knows javascript –  Oct 05 '16 at 12:26
  • @StephenMuecke Yup.. that's right. i was wrong .me just learning ... – Anil P Babu Jan 20 '17 at 09:21

0 Answers0