Only Digits: unsigned (positive) whole number. 1): Any size or pattern using a set function testExp(str) { var exp=/^ *[0-9]+ *$/; if (exp.test(str)) { alert('valid'); } } 2): 3 to 5 digits. function testExp(str) { var exp=/^\d{3,5}$/; if (exp.test(str)) { alert('valid'); } } 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. A number with leading and trailing spaces can be considered valid because conversion to numeric data will ignore the spaces. if you dont want to allow spaces then use this /^[0-9]*$/; The second regular expression with the addition of {3,5} that restricts the data to only 3 to 5 digits. signed integer: 1): Any size or pattern using a set function testExp(str) { var exp=/^[-+]?[0-9]+$/; if (exp.test(str)) { alert('valid'); } } 2): An optional sign and 3 to 5 digits function testExp(str) { var exp=/^[-+]?\d{3,5}$/; if (exp.test(str)) { alert('valid'); } } Decimal or Float: 1): Any size or pattern using a set function testExp(str) { var exp=/^[-+]?[0-9]+(\.[0-9]+)?$/; if (exp.test(str)) { alert('valid'); } } 2): Limited number of whole digits and decimals function testExp(str) { var exp=/^[-+]?\d{3,5}(\.\d{1,3})?$/; if (exp.test(str)) { alert('valid'); } }
Saturday, 27 August 2011
Regular expression for validating numbers
Labels:
dotnet
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment