JSFiddle - React, Tailwind, and code Playground

by mendesjuan

HTML

<input id='field'>

JavaScript

(function( $ ) {
    $.fn.restrict = function(regExp, additionalRestriction) {
        function restrictCharacters(myfield, e, restrictionType) {
            var code = e.which;
            var character = String.fromCharCode(code);
            // if they pressed esc... remove focus from field...
            if (code==27) { this.blur(); return false; }
            // ignore if they are press other keys
            // strange because code: 39 is the down key AND ' key...
            // and DEL also equals .
            if (!e.originalEvent.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
                if (character.match(restrictionType)) {
                    return additionalRestriction(myfield.value, character);
                } else {
                    return false;
                }
            }
        }
        this.keypress(function(e){
            if (!restrictCharacters(this, e, regExp)) {
                e.preventDefault();
            }
        });
    };
})( jQuery );

$('#field').restrict(/[0-9\.]/g, function (currentValue, newChar) {
    return !(currentValue.indexOf('.') != -1 && newChar == ".");    
});