9

I want to test for this input: [an optional negative sign] 2 digits [an optional . and an optional digit] like this:

-34 or -34.5333 or 34.53333 or 34 in JavaScript

This is what I came up with but it doesn't work!

/^(-)\d{2}(\.d\{1})$/

Can someone please help me?

8 Answers 8

15

Try this regex:

/^-?\d{2}(\.\d+)?$/
Sign up to request clarification or add additional context in comments.

1 Comment

some invalid numeric values pass the test with this regex : '-00.23', -0``
4

this regex matches any valid integer.

/^0$|^-?[1-9]\d*(\.\d+)?$/

you can modify this to suite your needs :

/^-?[1-9]\d{0,1}(\.[1-9]{1})?$/

this matches 2.1, 21.4, 3, 90...

Comments

3

Perhaps regex is not needed.

function validate(val){
    return isNaN(val)?false:(Math.abs(Math.floor(val)).toString().length==2);
}

Comments

0

Try this regex:

/^-?[0-9]{2}(?:\.[0-9]+)?$/

Comments

0

Try this:

/^(-)?\d{2}(\.\d+)?$/

Comments

0

You can use this regular expression:

-?\d{2}[.]?\d*

Comments

0

what your regEx ( /^(-)\d{2}(.d{1})$/ ) does is:

Start with requiring the negative and then correctly your requiring two digits, then with the "." your requiring any character, you should strict it to the symbol with "\", and finally comes one digit.

correct example code would be:

var str = '-34.23';
pat=/^\-?\d{2}(\.(\d)*)?$/g;
str.match(pat);

More testable example: http://jsfiddle.net/GUFgS/1/

use the "?" after the group to make that match an option i.e (\.\d*)?

Comments

0

This below simple html code will validate the +ve & -ve numbers of 2 digits plus optional minimum of 1 digit after decimal point.

JS Code:

    function validateNum() {
        var patForReqdFld = /^(\-)?([\d]{2}(?:\.\d{1,})?)$/;
        var value = document.getElementById('txtNum').value;

        if(patForReqdFld.test(value)) {
            alert('Valid Number: ' + value);
        } else {
            alert('Invalid Number: ' + value);
        }
    }

HTML Code:

    <label>Enter Number:&nbsp;</label>
    <input type="text" id="txtNum" onBlur="validateNum()"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.