简体   繁体   中英

How to decimal validation : restricting only two Numeric values to be entered?

there is a jsfiddle which restricts entering only two values after dot JSFiddle . I also need to restrict only two Numeric values before dot like i would like to have values like 55.66 etc.

how to do this in javascript? also allow only Numbers to be entered before and after dot

No need of keypress Instead use onblur and you could use the following regex

function validateFloatKeyPress(el, evt) {
    if (!/^\d\d\.\d\d$/.test(el.value)) {
        alert("Two digits before and after point please!");
    }
}

DEMO

 document.addEventListener('DOMContentLoaded', function () { document.getElementById('input').addEventListener('keypress', function (event) { var value = event.target.value + String.fromCharCode(event.keyCode); if (!(/^\\d{1,2}(\\.$|\\.\\d{1,2}$|$)/).test(value)) { event.preventDefault(); event.stopPropagation(); } }); }); 
 <input id="input" type="text" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM