Validating dates

4 years 10 months ago #95249 by StuartMark0
StuartMark0 created the topic: Validating dates

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?


Please Log in to join the conversation.

4 years 10 months ago - 4 years 10 months ago #95259 by tpartner
tpartner replied the topic: Validating dates
Assuming both questions are on the same page, place the following script in the source of the first date question:

<script type="text/javascript" charset="utf-8">
		var msg = 'Date 2 cannot be earlier than date 1!';
		// Identify the questions
		var q1ID = '{QID}';
		var q1 = $('#question'+q1ID+'');
		var q2 = $(q1).nextAll(''); 
		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() != '' && $('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) {

Tony Partner
Solutions, code and workarounds presented in these forums are given without any warranty, implied or otherwise.
Last Edit: 4 years 10 months ago by tpartner.
The following user(s) said Thank You: StuartMark0

Please Log in to join the conversation.

4 years 10 months ago #96262 by ahchouch
ahchouch replied the topic: Validating dates
and if the 02 questions aren't on the same page?

Please Log in to join the conversation.

Did you already participate in our community engagement survey?

We would like to know your opinion:

Start now

Start now!

Just create your account and start using Limesurvey today.

Register now
Join our Newsletter!