简体   繁体   中英

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.

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.

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.

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
function validateNumber(yournumber){
return (parseFloat(yournumber ) == parseInt(yournumber) &&  parseInt(yournumber))
}

此正则表达式将适用于除0以外的所有数字,但00将适用

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM