The CreatorCon Call for Content is officially open! Get started here.

Regex validation on integer field

richard38
Tera Guru

Hello, I'm trying add some validation to an integer field. The validation is for positive, whole numbers. I've found a regex example that works, but only for numbers 1-999.

      var regExTest = /^[1-9][0-9]*$/;      

      g_form.hideFieldMsg("u_regex_test", true);

     

      if(!regExTest.test(newValue)){

              g_form.setValue("u_regex_test", "");

              g_form.showFieldMsg("u_regex_test","Enter a valid integer", "error");      

      }

My understanding is that the '*' represents the number of items being validated, similar to adding {0, } for min/max numbers. I've tried this in various online regex validators and they all show that this validates correctly, but it doesn't work as anticipated. Am I missing something?

thank you

11 REPLIES 11

Thanks Abhinay, but this allows negatives and decimals.


I don't think this will allow negatives numbers and decimals. Because the meta character \D will return true if there is any non digit character that include '-' and '.'


drjohnchun
Tera Guru

Richard - the regex you have is correct and it has nothing to do with limiting to 999. I suspect the validation logic besides the regex may be the source of limitation. Your regex says



var regExTest = /^[1-9][0-9]*$/;



  1. it must start with a number 1 through 9 (this eliminates 0).
  2. the first digit may be followed by 0 or more digits 0 through 9.


In fact, it has no limit on the number of digits.



Please feel free to connect, follow, mark helpful, like, endorse.


John Chun, PhD PMP see John's LinkedIn profile


visit snowaid


You may want to check if "newValue" is being truncated before being tested.


Chuck Tomasi
Tera Patron

FYI - we just did part 1 of 2 on regular expressions on TechNow Ep 31 yesterday. Part 2 is in a few weeks.



TechNow Episode List