This simple html code below will check the required value, as well as + ve and -ve numbers for at least 1 digit, additionally optional 2 digits after the decimal point.
JS Code:
function validateNum() { var patForReqdFld = /^(\-)?([\d]+(?:\.\d{1,2})?)$/; var patForOptFld = /^(\-)?([\d]*(?:\.\d{1,2})?)$/; 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()"/>
source share