Javascript code to validate numeric integer only | XM Community
Skip to main content

I want to validate, that for certain answers in multiple form fields, only positive integer numbers can be entered AND that the values can be between 1 and 300

Hello there! I would recommend trying to leverage the Regex validation. Go to your survey project, then the text-entry question, and begin entering validation by looking at the Response Requirements. 

Add Custom Validation and then select the Regex option.

The Regex I was able to use was ^(?:?1-9]|]1-9]90-9]|]12]20-9]{2}|300)$

 

You can also go a different route, perhaps much easier, by adding Content Type Validation:

Let me know if this works for you! Thanks

 


Please note: this will only work on a form field question if all fields need to meet that 0 - 300 integer requirement. If not, you will need to separate them out so the validation can match. You can add basic validation to each form field in the question (see below), but to add the Regex or the min/max and decimal places, that will be done across the entire question, which includes all statements.

 


Thanks so much. I probably should have explained that my form fields are ‘carry forward’ from the previous question, presented as multiple choice with multiple options:

Q1 ‘Have you ever done
x
y
z

Q2

z (for example) - this is a form field.
From what I can see, I can’t have multiple text boxes to pick up the carry forward responses, so I’ve had to use multiple form fields. However, I don’t seem to be able to edit the validation of these form fields to numeric integer. It looks as though it might be possible with JavaScript, but I don’t know how.

 

 


Hi  @ElleJBee ,
I was able to find a JS solution for your query using regex provided by @tannerfaragher  , please add below JS code in the form field question:
 

Qualtrics.SurveyEngine.addOnload(function()
{
/*Place your JavaScript here to run when the page loads*/

});

Qualtrics.SurveyEngine.addOnReady(function()
{
let regex = /^(?:/1-9]|11-9][0-9]|012]|0-9]{2}|300)$/;

jQuery("#"+this.questionId+" input").on('input', function() {


if (regex.test(jQuery(this).val())) {
jQuery('#NextButton').show();
} else {
jQuery('#NextButton').hide();
}
});

});

Qualtrics.SurveyEngine.addOnUnload(function()
{
/*Place your JavaScript here to run when the page is unloaded*/

});


This code hides the "Next” button if regex does not mtaches.
Hope this resolves your query😊!!


Hey @ElleJBee and @qualtrics_nerd, glad we could work together to come up with a solution! Thanks for the context and helping me learn as well. Y’all are awesome!


@qualtrics_nerd @tannerfaragher 
Great - thank you so much, this works well. I now need to add an error message for when people don’t put in the right details.


Leave a Reply