Thursday, 27 October 2011

Saturday, 15 October 2011

Regular expression for validating numbers

Only Digits:

below expression is for unsigned (positive) whole number.

1): Any size or pattern

function testExp(str) {
                    return /^ *[0-9]+ *$/.test(str);
                }

2): 3 to 5 digits.
function test3(str) {
                    return /^\d{3,5}$/.test(str);
                }
The first regular expression allows one or more characters in the set [0-9] preceded or followed by any number of spaces within the length of the string. The metacharacters ^ and $ meaning beginning and end of string respectively excludes any characters other than specified in the pattern. A number with leading and trailing spaces can be considered valid because conversion to numeric data will ignore the spaces. However, it is a good idea to trim data before validating using alltrim covered previously.
The second pattern disallows leading and trailing spaces and is shorter because in uses the metacharacter \d for digits. If the data is trimmed before validating with an alltrim covered previously, data otherwise valid will pass this test.
The third regular expression is the same as the second with the addition of {3,5} that restricts the data to having 3 to 5 of the preceding character(s) in this case digits.
A signed integer: 
1): Any size; pattern using a set
function test1(str) {
                str = alltrim(str);
                return /^[-+]?[0-9]+$/.test(str);
            }

2): An optional sign and 3 to 5 digits
function test3(str) {
                str = alltrim(str);
                return /^[-+]?\d{3,5}$/.test(str);
            }

Decimal or Float 
1): Any size; pattern using a set
function test1(str) {
    str = alltrim(str);
    return /^[-+]?[0-9]+(\.[0-9]+)?$/.test(str);
}

2): Limited number of whole digits and decimals
function test3(str) {
    str = alltrim(str);
    return /^[-+]?\d{3,5}(\.\d{1,3})?$/.test(str);
}
The expressions again follow the pattern set forth in the previous examples. These differ only in the addition of test, (\.\d+) for a decimal point and decimals.