Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex (for jQuery) to validate positive numbers with 2 decimal points

I need to match a field with regex using jQuery. Currently I am using:

 onsubmit: function (settings, td) {
            //select integers only
            var intRegex = /[0-9 -()+]+$/;
            var input = $(td).find('input');
            var original = input.val();

            if (original <= 0) {
                Alert('The amount should be bigger than 0');
                return false;
            }
            if (!original.match(intRegex)) {
                Alert('Please enter a valid number');
                return false;
            }
            else {
                return true;
            }
        }

A string like "abc" does not pass the check. But invalid characters like @#$% or "/" do pass the check, which causes an error in my method.

I am looking for regex which:

Matches: 1.20, 1, 2.00, 3.1

Does not match: -1.2, abc, 1/2, $, @#$%

I browsed through the regex library, but if I put (^\d*\.?\d*[0-9]+\d*$)|(^[0-9]+\d*\.\d*$) inside my script, I get a syntax error...

like image 276
shennyL Avatar asked Dec 13 '22 07:12

shennyL


1 Answers

Use:

var intRegex = /^\d+(?:\.\d\d?)?$/;

That should work.

like image 114
fge Avatar answered Jan 31 '23 10:01

fge