Create an Only Number Field From String Field

kiley
Giga Contributor

So obviously ServiceNow still does not have restricted-to-numbers fields. I know I am not the only one who would like a basic or easy way of creating one, so does anyone have any ideas? Also, is it possible to have a field not accept letters at all, meaning if they try to type letters into the field they do not show up? I was thinking something along the lines of an "onChange" situation, but they would still be able to input the letters in the first place.

Thank you in advance!

1 ACCEPTED SOLUTION

Mike Allen
Mega Sage

Regex is the way to do this:



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



  if (isLoading ) {


  return;


  }



  if(oldValue != newValue){



  var VALIDCHARS = "1234567890";


  var number   = newValue.trim();


  var regEx = "^[0-9]*$";


  var rtn = number.match(regEx);


  g_form.hideFieldMsg('number', true);


  if (rtn == null) {


  g_form.showFieldMsg('number', number + " is an invalid   number, please re-enter using only characters from " + VALIDCHARS ,'error');


  return;


  }


  }



}


View solution in original post

3 REPLIES 3

Mike Allen
Mega Sage

Regex is the way to do this:



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



  if (isLoading ) {


  return;


  }



  if(oldValue != newValue){



  var VALIDCHARS = "1234567890";


  var number   = newValue.trim();


  var regEx = "^[0-9]*$";


  var rtn = number.match(regEx);


  g_form.hideFieldMsg('number', true);


  if (rtn == null) {


  g_form.showFieldMsg('number', number + " is an invalid   number, please re-enter using only characters from " + VALIDCHARS ,'error');


  return;


  }


  }



}


kiley
Giga Contributor

I am a little confused about rtn. Does that determine if the input matches the regEx setup? Is groupPhone your variable?


Sorry, I pulled it from a phone number field and tried to genericize.   Let me look at it.



It would be number.match in this.