Abdul Jabbar
Abdul Jabbar

Reputation: 5971

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.

Upvotes: 4

Views: 11398

Answers (5)

Avinash Raj
Avinash Raj

Reputation: 174874

Use a negative lookahead at the start.

/^(?!0)\d+$/.test(value);

This regex won't match the string if it contain 0 at the start.

Upvotes: 2

Spectator
Spectator

Reputation: 79

This regex will work with all digits except 0 but 00 will work

/([0-9]{2,})|[1-9]/.test(value);

Upvotes: 0

Vladu Ionut
Vladu Ionut

Reputation: 8193

function validateNumber(yournumber){
return (parseFloat(yournumber ) == parseInt(yournumber) &&  parseInt(yournumber))
}

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59292

There is no need for a regex. Just make use of Number function or + unary operator to convert it into an actual number and see if it's less than 1 and greater than -1

value = +value; // it's now a number
var bool = value < 1 && value > -1;  // less than 1 but greater than -1

Upvotes: 1

Stefano Sanfilippo
Stefano Sanfilippo

Reputation: 33116

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.

Upvotes: 12

Related Questions