DataAnnotations for checking between Start Time and End Time

6

I have two fields of type [DataType (DataType.Time)], being the Start Date and End Date, and I can not let the user enter the Final Date smaller than the Start Date for the purpose of calculating hours worked. p>

How do I compare two time fields with DataAnnotations.

  • can be customized
  • or already existing within the MVC Asp.Net that I do not know already exists.

Thank you in advance

I'm waiting for you

    
asked by anonymous 23.12.2016 / 18:09

1 answer

7

Server Side

You can make a comparison between two dates with a custom DataAnnotation, here is a basic example, but you already have an idea 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 };
      }

   }
}

Then when you use 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 must first, in your Data Annotation class, implement the IClientValidatable , which is a simple interface with only one method, GetClientValidationRules , which is used to return the validation rules on the side client of the class that implements it.

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 be validating):

(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 usage examples and each of the IClientValidatable properties I recommend reading this post CUSTOM UNOBTRUSIVE JQUERY VALIDATION WITH DATA ANNOTATIONS IN MVC 3 , which despite being with MVC3, also works for newer versions of MVC.

    
23.12.2016 / 18:45