Restrict //JavaScript Repository

Description

Class to mask inputs and restrict characters.
Created: 2005.10.08 - Modified 2013.09.17

Dependencies

Code (Download)

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/forms/restrict [rev. #2]

Restrict = function(form){
    this.form = form, this.field = {}, this.mask = {};
}
Restrict.field = Restrict.inst = Restrict.c = null;
Restrict.prototype.start = function(){
    var $, __ = document.forms[this.form], s, x, j, c, sp, o = this, l;
    var p = {".":/./, w:/\w/, W:/\W/, d:/\d/, D:/\D/, s:/\s/, a:/[\xc0-\xff]/, A:/[^\xc0-\xff]/};
    for(var _ in $ = this.field)
        if(/text|textarea|password/i.test(__[_].type)){
            x = $[_].split(""), c = j = 0, sp, s = [[],[]];
            for(var i = 0, l = x.length; i < l; i++)
                if(x[i] == "\\" || sp){
                    if(sp = !sp) continue;
                    s[j][c++] = p[x[i]] || x[i];
                }
                else if(x[i] == "^") c = (j = 1) - 1;
                else s[j][c++] = x[i];
            o.mask[__[_].name] && (__[_].maxLength = o.mask[__[_].name].length);
            __[_].pt = s, addEvent(__[_], "keydown", function(e){
                var r = Restrict.field = e.target;
                if(!o.mask[r.name]) return;
                r.l = r.value.length, Restrict.inst = o; Restrict.c = e.key;
                setTimeout(o.onchanged, r.e = 1);
            });
            addEvent(__[_], "keyup", function(e){
                (Restrict.field = e.target).e = 0;
            });
            addEvent(__[_], "keypress", function(e){
                o.restrict(e) || e.preventDefault();
                var r = Restrict.field = e.target;
                if(!o.mask[r.name]) return;
                if(!r.e){
                    r.l = r.value.length, Restrict.inst = o, Restrict.c = e.key || 0;
                    setTimeout(o.onchanged, 1);
                }
            });
        }
}
Restrict.prototype.restrict = function(e){
    var o, c = e.key, n = (o = e.target).name, r;
    var has = function(c, r){
        for(var i = r.length; i--;)
            if((r[i] instanceof RegExp && r[i].test(c)) || r[i] == c) return true;
        return false;
    }
    var inRange = function(c){
        return has(c, o.pt[0]) && !has(c, o.pt[1]);
    }
    return (c < 30 || inRange(String.fromCharCode(c))) ?
        (this.onKeyAccept && this.onKeyAccept(o, c), !0) :
        (this.onKeyRefuse && this.onKeyRefuse(o, c),  !1);
}
Restrict.prototype.onchanged = function(){
    var ob = Restrict, si, moz = false, o = ob.field, t, lt = (t = o.value).length, m = ob.inst.mask[o.name];
    if(o.l == o.value.length) return;
    if(si = o.selectionStart) moz = true;
    else if(o.createTextRange){
        var obj = document.selection.createRange(), r = o.createTextRange();
        if(!r.setEndPoint) return false;
        r.setEndPoint("EndToStart", obj); si = r.text.length;
    }
    else return false;
    for(var i in m = m.split(""))
        if(m[i] != "#")
            t = t.replace(m[i] == "\\" ? m[++i] : m[i], "");
    var j = 0, h = "", l = m.length, ini = si == 1, t = t.split("");
    for(i = 0; i < l; i++)
        if(m[i] != "#"){
            if(m[i] == "\\" && (h += m[++i])) continue;
            h += m[i], i + 1 == l && (t[j - 1] += h, h = "");
        }
        else{
            if(!t[j] && !(h = "")) break;
            (t[j] = h + t[j++]) && (h = "");
        }
    o.value = o.maxLength > -1 && o.maxLength < (t = t.join("")).length ? t.slice(0, o.maxLength) : t;
    if(ob.c && ob.c != 46 && ob.c != 8){
        if(si != lt){
            while(m[si] != "#" && m[si]) si++;
            ini && m[0] != "#" && si++;
        }
        else si = o.value.length;
    }
    !moz ? (obj.move("character", si), obj.select()) : o.setSelectionRange(si, si);
}

Example (Example)

<form id="form" action=" " method="post">
    <input type="text" name="a" maxlength="10" /><br />
    Restri??o = (\\d/) Somente n?meros e "/"<br />M?scara = ##/##/####<br /><br />
    <input type="text" name="b" maxlength="14" /><br />
    Restri??o = (\\d.-) Somente n?meros, ponto e h?fen<br />M?scara = ###.###.###-##<br /><br />
    <textarea name="c" cols="4" rows="5" style="width: 300px; height: 120px;"></textarea><br />
    Restri??o = (a\\^bc) Somente os caracteres "a", "b", "c" e "^"
</form>

<script type="text/javascript">
//<![CDATA[

    var r = new Restrict("form");
    r.field.a = "\\d/";
    r.mask.a = "##/##/####";
    r.field.b = "\\d.-";
    r.mask.b = "###.###.###-##";
    r.field.c = "a\\^bc";
    r.onKeyRefuse = function(o, k){
        o.style.backgroundColor = "#fdc";
    }
    r.onKeyAccept = function(o, k){
        if(k > 30)
            o.style.backgroundColor = "transparent";
    }
    r.start();

//]]>
</script>

Help

Constructor

Restrict(form: String)
Generates an instance of Restrict.
form
name or id of the form that will receive the validations
String.mask(mask: String): String
Returns a string with the mask applied.
mask
mask that will be used

Properties

Restrict.mask: Object
This property is used to mask the fields and must be used as the following example:
instanceOfRestrict.mask.nameOfTheFieldInTheForm = mask.
Where mask follow the following rules:
  • The class replaces each "#" character in the mask by the key that the user pressed.
    Ex: mask = "##/##/####" (to mask a date)
  • As the "#" has a special meaning, if you need to use it as part of the mask, just comment it out with "\\". Ex: "\\#".
  • The mask is applied from the left to the right, if the field has less characters than the mask, the "extra" characters of the mask will be ignored.
  • If the field has more characters than the mask, the remaining characters of the field will be added to the end of the mask.
Restrict.field: Object
This property is used to filter the characters that can be inserted into the field.
Must be used as the following example:
instanceOfRestrict.field.nameOfTheFieldInTheForm = filter.
Where filter follow the following rules:
  • The filter is applied just to the character that was pressed out, and it's simple to use it, just type the characters that you want to allow.
    Ex: filter = "9aA." (will allow typing the characters "9", "a", "A", and ".")
  • However, it would be bad to type all the alphabet characters in a field that must allow only letters, hence, there are pre-defined regular expressions in the class:
    • "." = Any character
    • "w": Only A-z, a-z, 0-9 and _
    • "W": Any character, except: A-z, a-z, 0-9 and _
    • "d": 0-9
    • "D": Any character, except 0-9
    • "s": Allows white space, tab, line break, etc. (\f\n\r\t\v)
    • "a": Allows only letters with accent
    • "A": Allows any character, except letters with accent

    If you need more rules, just define them on the source code.
    To use the regular expressions, just prefix the name of the rule with "\\".
    Ex: filter = "\\d\\s" (allows numbers and white spaces)
  • It's also possible to specify exceptions for the filter by using the character "^".
    Ex: filter = "\\d^123" (allows 0-9, except the characters 1, 2 and 3)
  • The bar "\\" and the "^" have a special meaning for the filter, if you need to use them as simple characters, just comment them with "\\" as in the example bellow:
    Ex: filter = "\\\\" (allows the bar)
    filter = "\\^" (allows the circumflex)

Methods

Restrict.start(void): void
Prepares the object. Must be called after all the rules are already setted.

Events

Restrict.onKeyRefuse: function(field: HTMLInputElement, keyCode: Integer): void
This event is called whenever the user press an invalid key.
field
field that is beeing edited
keyCode
key code
Restrict.onKeyRefuse: function(field: HTMLInputElement, keyCode: Integer): void
This event is called whenever the user press a valid key.
field
field that is beeing edited
keyCode
key code

Rank (Votes: 94)

4.20