You are viewing limited content. For full access, please sign in.

Question

Question

Validate if end date is greater than start date in forms

asked on November 26, 2019

Is there a way to validate using formula in forms if end date field is greater than start date?

 

Thanks

Priya

0 0

Replies

replied on November 26, 2019

Hi Priya,

Here is a great stackoverflow post on how to accomplish it with JavaScript. If you're not familiar with the syntax in the article then it's just vanilla JavaScript without any libraries or frameworks. There is a tendency to use jQuery for LF Forms since it's already integrated but there is no issue with using the 'vanilla' syntax either

https://stackoverflow.com/questions/40819789/how-to-compare-two-dates-from-input

0 0
replied on November 26, 2019 Show version history

Although you can do it with vanilla javascript, the "best" methods in my opinion are to use either a custom Parsley validator or leverage the min date attribute of the end date field as both mimic the behavior of the built-in error messages, including preventing form submission.

  // Custom validator for date range
  window.Parsley.addValidator('daterangevalidation', {
    validateString: function(value) {
      var allowed = true;

      if($('.startDate input').val() !== '' && $('.endDate input').val() !== ''){
        return Date.parse($('.startDate input').val()) <= Date.parse($('.endDate input').val());
      }

      return allowed;
    },
    messages: {
      en: 'End date must be after start date.',
    }
  });

  // Assign validator to date fields
  $('.startDate input').attr('data-parsley-daterangevalidation','');
  $('.endDate input').attr('data-parsley-daterangevalidation','');

I'd say the better way is to just add a change event to the start date field that modifies the allowable range for the end date.

  $('.startDate input').change(function(){
    var startDate = $('.startDate input').val();
    
    if(startDate != ''){
      var d = new Date(Date.parse(startDate));      
      var dmy = [d.getDate(),d.getMonth() + 1,d.getFullYear()];
      
      // Format date
      for (var n = 0; n < 2; n++){
        if (dmy[n].toString().length < 2){
          dmy[n] = "0" + dmy[n];
        }
      }
      
      $('.endDate input').attr('min',(dmy[2] + "-" + dmy[1] + "-" + dmy[0]));
      
      if($('.dateRange select').val() == 'Between' && $('.endDate input').val() != ''){
        $('.endDate input').parsley().validate();
      }
    }
  });

Which would also give you an error message and prevent submission. Combine that with a custom error message in the Error Messages tab

and you get,

2 0
replied on December 2, 2019

@Jason Smith Great response & write up!! Very successful with the 2nd option. Much appreciated.

0 0
replied on November 26, 2019

Thanks. I was wondering if it was possible to do this using formulas in Forms

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.