Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate email as you type

I want to validate input as I type so I use onkeyup event to do so, but if I validate an email regex "[email protected]", as soon as user starts to type it throws an error - first character doesnt match regex...

So I wrote this:

var addValidation = function (patterns) {
        var index = patterns.length; //I know I can avoid this
        while (index--) {
            patterns[index] = new RegExp(patterns[index]);
        }

        index = 0;
        var current = patterns[index],
        matchExact = function (patt, str) {
            var match = str.match(patt);
            return match !== null && str === match[0];
        };

        return function () {
            var str = this.value;
            if (!matchExact(current, str) ) {
                var tmp = patterns[index + 1] ? 
                    new RegExp(current.source + patterns[index + 1].source) :
                    false;
                if (tmp && matchExact(tmp, str)) {
                    current = tmp;
                    index++;
                }
                else {
                    alert("Wrong");
                }
            }
        }
    };
    document.getElementById("x").onkeyup = addValidation(["[a-zA-Z0-9\\.]+", "@{1}", "[a-zA-Z0-9]+", "\\.{1}", "[a-zA-Z]{1,3}"]);

It seems to work, but... it's ugly and it will alert you if you do step back (eg. "name@" and you press backspace).

I know that Dojo's validation is great, but I do not want to use Dojo. Are there any better ways to achieve that?

//EDIT: http://livedocs.dojotoolkit.org/dijit/form/ValidationTextBox this is an example, but you can define your own pattern (like email regex) and it will validate it perfectly.

like image 417
Tondo Avatar asked Dec 07 '25 06:12

Tondo


1 Answers

Add interval before validation will start:

var t;
document.getElementById("x").onkeyup = function () {
    if (t) {
        clearTimeout(t);
    }
    t = setTimeout(function () {
        //do validation
    }, 1000)
}
like image 81
CruorVult Avatar answered Dec 09 '25 20:12

CruorVult