Over a million developers have joined DZone.

Masked Input //Javascript Object

·

Simple and generic mask routine.

[UPDATED CODE AND HELP CAN BE FOUND HERE]



@REQUIRES Event-Listener


// REQUIRES: http://jsfromhell.com/geral/event-listener

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/forms/masked-input [v1.0]

MaskInput = function(f, m){ //v1.0
    function mask(e){
        var patterns = {"1": /[A-Z]/i, "2": /[0-9]/, "4": /[À-ÿ]/i, "8": /./ },
            rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
        function accept(c, rule){
            for(var i = 1, r = rules[rule] || 0; i <= r; i<<=1)
                if(r & i && patterns[i].test(c))
                    break;
                return i <= r || c == rule;
        }
        var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
        (!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ?
            r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
            : (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
            r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
    }
    for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1})
        addEvent(f, i, mask);
};

//]]>




Usage (sorry, i'm lazy to write a help hahaha)


telephone "(99)9999-9999" date "99/99/9999" máscara = letter + letter withou accent + 2 numbers + "-" + anything + letter "Cc99-*C" everything, but a, b or c "E^abc" only a, b or c "O^abc" just letters "C^" just letters and also white-space "C^ " just numbers and also the letters a, b e c "9^abc"
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}