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!
开发者_JS百科/^(-)\d{2}(\.d\{1})$/
Can someone please help me?
Try this regex:
/^-?\d{2}(\.\d+)?$/
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...
Perhaps regex is not needed.
function validate(val){
return isNaN(val)?false:(Math.abs(Math.floor(val)).toString().length==2);
}
Try this regex:
/^-?[0-9]{2}(?:\.[0-9]+)?$/
Try this:
/^(-)?\d{2}(\.\d+)?$/
You can use this regular expression:
-?\d{2}[.]?\d*
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*)?
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: </label>
<input type="text" id="txtNum" onBlur="validateNum()"/>
精彩评论