Input Restriction

Disables paste & limits the characters which can be input into a textbox.

by Troy Alford

HTML

<span>Numbers only!</span><input type="text" restriction="numeric" /><br />
<span>Letters only!</span><input type="text" restriction="alpha" /><br />
<span>Alphanumeric!</span><input type="text" restriction="alphanumeric" /><br />
<span>Names!</span><input type="text" restriction="names" /><br />

SCSS

body { padding: 15px; }
span { display: inline-block; width: 100px; }

JavaScript

$('input[restriction]').on('keypress paste', function (ev) {
    var $el = $(ev.target);
    
    if (ev.type == 'paste') {
        ev.preventDefault();
        return false;
    }
    
    var regexes = {
        alpha: /^[a-zA-Z]*$/,
        numeric: /^[0-9]*$/,
        alphanumeric: /^[0-9a-zA-Z]*$/,
        names: /^[a-zA-Z '`-]*$/
    };
    
    var restriction = $el.attr('restriction').trim().toLowerCase();
    var newValue = String.fromCharCode(ev.keyCode);

    if (!restriction || !regexes[restriction] || newValue.match(regexes[restriction]))
        return true;
    else
        return false;
});