Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to allow all Numbers but not if only 0 in Javascript

I have been trying to figure out how to return true if any number but not if only 0 or contains any decimal . that is

1    //true
23   //true
10   //true
0.2  //false
10.2 //false
02   //false
0    //false

I have made this regex so far and it's working fine but it also allows 0 which I don't want

/^[0-9]+$/.test(value);

I tried to search my best and tried these regex so far but failed

/^[0]*[0-9]+$/
/^[0-9]+[^0]*$/

I am not good in regex at all. Thank you anticipation.

like image 992
Airy Avatar asked Sep 05 '25 03:09

Airy


1 Answers

You were close: /^[1-9][0-9]*$/.

The leading [1-9] forces the number to have a most-significant digit which is not 0, so 0 will not be accepted. After that, any digit can come.

Finally, a number containing . is not accepted.

like image 127
Stefano Sanfilippo Avatar answered Sep 07 '25 20:09

Stefano Sanfilippo