Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to only allow numbers under 10 digits?

I'm trying to write a regex to verify that an input is a pure, positive whole number (up to 10 digits, but I'm applying that logic elsewhere).

Right now, this is the regex that I'm working with (which I got from here):

 ^(([1-9]*)|(([1-9]*).([0-9]*)))$

In this function:

if (/^(([1-9]*)|(([1-9]*).([0-9]*)))$/.test($('#targetMe').val())) {
            alert('we cool')
        } else {
            alert('we not')
        }

However, I can't seem to get it to work, and I'm not sure if it's the regex or the function. I need to disallow %, . and ' as well. I only want numeric characters. Can anyone point me in the right direction?

like image 615
streetlight Avatar asked Jan 07 '13 13:01

streetlight


People also ask

What does \+ mean in regex?

For examples, \+ matches "+" ; \[ matches "[" ; and \. matches "." . Regex also recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.

How do I select only numbers in regex?

If you want to get only digits using REGEXP, use the following regular expression( ^[0-9]*$) in where clause. Case 1 − If you want only those rows which have exactly 10 digits and all must be only digit, use the below regular expression.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


2 Answers

You can do this way:

/^[0-9]{1,10}$/

Code:

var tempVal = $('#targetMe').val();
if (/^[0-9]{1,10}$/.test(+tempVal)) // OR if (/^[0-9]{1,10}$/.test(+tempVal) && tempVal.length<=10) 
  alert('we cool');
else
  alert('we not');

Refer LIVE DEMO

like image 86
Siva Charan Avatar answered Sep 28 '22 12:09

Siva Charan


var value = $('#targetMe').val(),
    re    = /^[1-9][0-9]{0,8}$/;

if (re.test(value)) {
    // ok
}
like image 34
Fabrizio Calderan Avatar answered Sep 28 '22 11:09

Fabrizio Calderan