streetlight
streetlight

Reputation: 5968

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?

Upvotes: 8

Views: 88187

Answers (7)

pankaj
pankaj

Reputation: 1914

check this site here you can learn JS Regular Expiration. How to create this?

https://www.regextester.com/99401

Upvotes: -1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123428

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

if (re.test(value)) {
    // ok
}

Upvotes: 8

Krucamper
Krucamper

Reputation: 371

  var reg      = /^[0-9]{1,10}$/;
  var checking = reg.test($('#number').val()); 

  if(checking){
    return number;
  }else{
    return false;
  }

Upvotes: 3

Sunil Acharya
Sunil Acharya

Reputation: 1183

Use this regular expression to match ten digits only:

@"^\d{10}$"

To find a sequence of ten consecutive digits anywhere in a string, use:

@"\d{10}"

Note that this will also find the first 10 digits of an 11 digit number. To search anywhere in the string for exactly 10 consecutive digits.

@"(?<!\d)\d{10}(?!\d)"

Upvotes: 0

Siva Charan
Siva Charan

Reputation: 18064

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

Upvotes: 23

KooiInc
KooiInc

Reputation: 122986

Would you need a regular expression?

var value = +$('#targetMe').val();
if (value && value<9999999999) { /*etc.*/ }

Upvotes: 3

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174467

That's the problem with blindly copying code. The regex you copied is for numbers including floating point numbers with an arbitrary number of digits - and it is buggy, because it wouldn't allow the digit 0 before the decimal point.

You want the following regex:

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

Upvotes: 1

Related Questions