Welcome, Guest
Username: Password: Remember me

TOPIC: Validating dates

Validating dates 1 year 5 months ago #95249

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 administrator has disabled public write access.

Validating dates 1 year 5 months ago #95259

  • tpartner
  • tpartner's Avatar
  • OFFLINE
  • LimeSurvey Team
  • Posts: 4271
  • Thank you received: 805
  • Karma: 369
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">
	$(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() != '' && $('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.

LimeSurvey is open-source and run entirely by volunteers so please consider donating to support the project.
Last Edit: 1 year 5 months ago by tpartner.
The administrator has disabled public write access.
The following user(s) said Thank You: StuartMark0

Validating dates 1 year 5 months ago #96262

  • ahchouch
  • ahchouch's Avatar
  • OFFLINE
  • Junior Lime
  • Posts: 22
  • Karma: 0
Hi
and if the 02 questions aren't on the same page?
The administrator has disabled public write access.
Moderators: ITEd
Time to create page: 0.108 seconds
Donation Image