Dataannotations for checking between Start Time and End Time

Asked

Viewed 843 times

6

I have two fields of type [Datatype(Datatype.Time)], being Start Date and End Date, and I cannot let the user enter the End Date less than the Start Date for the purpose of calculating hours worked.

How do I compare two time fields with Dataannotations.

  • can be customized
  • or already existing within MVC Asp.Net that I don’t know already exists.

Thanks in advance

I stand by

1 answer

7


Server-side

You can make a comparison between two dates with a custom Dataannotation, here is a basic example, but you can already get an idea of how to compare the dates:

using System;
using System.ComponentModel.DataAnnotations;

namespace Test
{
   [AttributeUsage(AttributeTargets.Property)]
   public class DateGreaterThanAttribute : ValidationAttribute, IClientValidatable
   {

      private string DateToCompareFieldName { get; set; }

      public DateGreaterThanAttribute(string dateToCompareFieldName)
      {
          DateToCompareFieldName = dateToCompareFieldName;
      }

       protected override ValidationResult IsValid(object value, ValidationContext validationContext)
       {
           DateTime laterDate = (DateTime)value;

           DateTime earlierDate = (DateTime)validationContext.ObjectType.GetProperty(DateToCompareFieldName).GetValue(validationContext.ObjectInstance, null);

           if (laterDate > earlierDate)
           {
               return ValidationResult.Success;
           }
           else
           {
               return new ValidationResult(string.Format("{0} precisa ser menor!", DateToCompareFieldName));
           }
       }
       
       //esse método retorna as validações que serão utilizadas no lado cliente
       public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
       {
           var clientValidationRule = new ModelClientValidationRule()
           {
               ErrorMessage = string.Format("{0} precisa ser menor!", DateToCompareFieldName),
               ValidationType = "dategreaterthan"
           };

       clientValidationRule.ValidationParameters.Add("datetocomparefieldname", DateToCompareFieldName);

          return new[] { clientValidationRule };
      }

   }
}

There when you will use in the properties you want to compare:

public DateTime DataInicial { get; set; }

[DateGreaterThan("DataInicial")]
public DateTime DataFinal{ get; set; }

Client side

For client-side validation, you should first, in your Data Annotation class, implement the interface Iclientvalidatable, which is a simple interface with only one method, Getclientvalidationrules, which is used to return the client-side validation rules of the implementing class.

you should also create a separate file that will contain your field validation code, for example

dateGreaterThanValidation.js

and put the code to create the validation (do not forget to reference this file on the page where you will do the validation):

(function ($) {
  $.validator.addMethod("dategreaterthan", function (value, element, params) {
      var otherProp = $('#' + params)
      return Date.parse(value) < Date.parse(otherProp.val());
  });
  
  $.validator.unobtrusive.adapters.add("dategreaterthan", ["datetocomparefieldname"], function (options) {
    options.rules["dategreaterthan"] = "#" + options.params.datetocomparefieldname;
    options.messages["dategreaterthan"] = options.message;
});

} (jQuery));

For more detailed information of examples of use and each of the properties of Iclientvalidatable I recommend reading this post CUSTOM UNOBTRUSIVE JQUERY VALIDATION WITH DATA ANNOTATIONS IN MVC 3, that despite being with MVC3, works also for the latest versions of MVC.

  • Amigo @Gabriel Weber the above code works perfectly, this validating according to my need.

  • Amigo @Gabriel Weber the above code works perfectly, this validating as my need. But I found a little problem, I would like to have another help from you. The Validator error message does not occur at the same time as the validation of the other fields. Explaining better, I have 3 fields Date, Start Time, End Time, if this case happens. Do not fill in Date and fill in Start Date = 6:00 and End Date = 5:00, only the Required of the Date field appears and in this case the Start Date is higher than the End Date, then the validation should also appear.

  • @cyberlacs updated my response. What was happening is that the original class I answered contained only server-side validation, so it only validated after all the client-side validations occurred. Try to see my answer and anything gives a read in the post I Linkei at the end of the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.