Adding Validations to Token Fields

More
4 years 3 months ago #89253 by LSCitizen
Can validation (like regular expression) be added to token fields?

For example, I want to create a token field called Date of Birth, but I want the format of the date to be in MM-DD-YYYY format.
Can I add a regular expression like /^\d{2}-\d{2}-\d{4}$/?

Please Log in to join the conversation.

More
4 years 3 months ago #89254 by c_schmitz
No sorry, this is currently not possible.

Best regards

Carsten Schmitz
LimeSurvey project leader

Please Log in to join the conversation.

More
4 years 3 months ago - 4 years 3 months ago #89317 by tpartner
As c_schmitz says, you can't do this server-side but there are several client-side solutions. (It should be noted that these would only work if JavaScript is enabled in the respondent's browser and they don't actively hack the JS)

1) Validate the input before submitting the form. Add something like the following to the end of template.js. Replace "attribute_1" with your attribute field. (This snippet was developed for the default template and may need to be modified for others):
$(document).ready(function(){
 
	$('.register-form form').submit(function(){
 
		var attributeField = 'attribute_1';
		var errorMessage = 'Please use date format mm-dd-yyyy'; 
 
		var validFormat = /^(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])-(19|20)\d\d$/; 
 
		// Test date format
		if(!validFormat.test($('input[name="register_'+attributeField+'"]').val())) {
			alert(errorMessage);
			return false;
		}
	});
 
});

2) Use a jQuery date picker :
$(document).ready(function(){
 
	var attributeField = 'attribute_1';
 
	$('input[name="register_'+attributeField+'"]').datepicker({ 
		dateFormat: 'mm-dd-yy'
	}).attr('readonly', true);
 
});

3) Use an input mask - digitalbush.com/projects/masked-input-plugin/

Cheers,
Tony Partner

Solutions, code and workarounds presented in these forums are given without any warranty, implied or otherwise.
Last Edit: 4 years 3 months ago by tpartner.

Please Log in to join the conversation.