Welcome to the LimeSurvey Community Forum

Ask the community, share ideas, and connect with other LimeSurvey users!

Validating dates

  • StuartMark0
  • StuartMark0's Avatar Topic Author
  • Offline
  • New Member
  • New Member
More
10 years 10 months ago #95249 by StuartMark0
Validating dates was created by StuartMark0
Howdy,

I have two dates from Date/Time questions, I'd like to ensure respondants to the survey cannot respond with the second of the two dates occuring before the first of the two dates.

i.e. in US date format 02-03-2013, 02-01-2013 would trigger an alert

Is there javascript avaliable which implements this?

Thanks
The topic has been locked.
  • tpartner
  • tpartner's Avatar
  • Offline
  • LimeSurvey Community Team
  • LimeSurvey Community Team
More
10 years 10 months ago - 10 years 10 months ago #95259 by tpartner
Replied by tpartner on topic Validating dates
Assuming both questions are on the same page, place the following script in the source of the first date question:

Code:
<script type="text/javascript" charset="utf-8">
  $(document).ready(function(){
 
    var msg = 'Date 2 cannot be earlier than date 1!';
 
    // Identify the questions
    var q1ID = '{QID}';
    var q1 = $('#question'+q1ID+'');
    var q2 = $(q1).nextAll('div.date:eq(0)'); 
    var q2ID = $(q2).attr('id').split('question')[1];
 
    // Listeners on the date inputs
    $('#question'+q1ID+' input[type="text"], #question'+q2ID+' input[type="text"]').change(function(){
      if($('input[type="text"]', q1).val() != '' &amp;&amp; $('input[type="text"]', q2).val() != '') {
        // Build date objects from the input values (format: mm-dd-yyyy)
        var d1Day = Number($('input[type="text"]', q1).val().split('-')[1]);
        var d1Month = Number($('input[type="text"]', q1).val().split('-')[0]) - 1;
        var d1Year = Number($('input[type="text"]', q1).val().split('-')[2]);
        var d1 = new Date(d1Year,d1Month,d1Day);
        var d2Day = Number($('input[type="text"]', q2).val().split('-')[1]);
        var d2Month = Number($('input[type="text"]', q2).val().split('-')[0]) - 1;
        var d2Year = Number($('input[type="text"]', q2).val().split('-')[2]);
        var d2 = new Date(d2Year,d2Month,d2Day);
        // Compare the date objects
        if(d1 > d2) {
          alert(msg);
          $(this).val('');
        }
      }
    });
  });
</script>

Cheers,
Tony Partner

Solutions, code and workarounds presented in these forums are given without any warranty, implied or otherwise.
Last edit: 10 years 10 months ago by tpartner.
The following user(s) said Thank You: StuartMark0
The topic has been locked.
More
10 years 9 months ago #96262 by ahchouch
Replied by ahchouch on topic Validating dates
Hi
and if the 02 questions aren't on the same page?
The topic has been locked.

Lime-years ahead

Online-surveys for every purse and purpose