allow only integer in a variable

leahp
Kilo Guru

I have a wizard that has several variables that should only allow the user to enter numeric values.  

How I do enforce that in a wizard client script?

1 ACCEPTED SOLUTION

Jim Coyne
Kilo Patron

It depends on how you want to implement it exactly, but an onChange Catalog Client Script on the variable should do the trick:



function onChange(control, oldValue, newValue, isLoading) {


  if (isLoading || newValue == ""){


      return;


  }



  //verify what was entered by using ServiceNow method that returns numeric characters only


  var parsed = g_form.getIntValue("number_variable");


  //if "Not a Number", clear the parsed value


  if (isNaN(parsed)){


      parsed = "";


  }



  //if the input and parsed values are different, set the variable value to the parsed value


  if (parsed != newValue) {


      alert("Please enter a valid integer number - stripping out non-numeric characters");


      g_form.setValue("number_variable", parsed);


  }


}



The above example will verify what was entered and if any non-numeric characters were input, will strip them out of the variable and pop-up an alert message.   Another way to do it would be just display an error message under the field without modifying it and then have an onSubmit script that would do the final check on all your variables to make sure they are integers.   Again, it all depends on how you want the user experience to be.



You could also inject some JavaScript into the input fields that only allows numbers to be entered, but that might be a little risky.



It's surprising there is still no OOB number variables for the catalog.


View solution in original post

13 REPLIES 13

Kevin:


Your solution works, except for the unfortunate side effect of not allowing the editting of numbers in the variable once they are entered.   If my user makes a mistake and types in "32" instead of just "3", they cannot remove the offending 2.


Hi Craig.


We do not experience this effect in our instances. We are able to edit the field after submission just like any other field. It appears something with the function may be erroring in your system and thus causing the field to become read only? Not sure. We are using CMS for our portal. If you are using ServicePortal maybe that's the difference?


We are in fact using ServicePortal in our instance ... perhaps that it the issue.



CrS


GM5
Giga Guru

A little bit late, there is already an OOTB feature to validate this it's called "Variable validation Regex" no code is needed.

  • Basically you define or use the ones that came OOTB like "Number" (this only only allow Integer positive numbers only) Here is how to Link

find_real_file.png

  • Then you add this new Validation Regex to your variable like this:

find_real_file.png