How to validate numbers use the regular expression JQuery?
Hi folks, in most of the cases we are facing issues with the validation of a positive number using JQuery. Sometimes you find a solution but when you apply that not work properly. But I am posting a great solution for it.
Let’s example we have a string xyz and we want to validate whether this string is a positive number or not. In this case, we use regular expression and it returns true or false.
/^\d+(?:.\d\d?)?$/
this is to validate the positive number with two decimal places.
/^\-?\d+(\.\d+)?$/
this is to validate the positive number with more than one decimal place.
const intRegex = /^\d+(?:\.\d\d?)?$/;
//OR
const intRegex = /^\-?\d+(\.\d+)?$/;
intRegex.test( '123.45' ); //True
intRegex.test( '123' ); //True
intRegex.test( '123.45' ); //True
intRegex.test( '123.123' ); //True
intRegex.test( '12.34.56' ); //False
intRegex.test( '-123.45' ); //False
intRegex.test( '-123' ); //False
intRegex.test( 'e' ); //False
intRegex.test( 'NULL' ); //False
intRegex.test( '12abc' ); //False
intRegex.test( '12,345.45' ); //False