Take the 2-minute tour ×

I want to validate input as I type so I use onkeyup event to do so, but if I validate an email regex "name@domain.com", 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) :
                if (tmp && matchExact(tmp, str)) {
                    current = tmp;
                else {
    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.

share|improve this question
add comment

2 Answers

Add interval before validation will start:

var t;
document.getElementById("x").onkeyup = function () {
    if (t) {
    t = setTimeout(function () {
        //do validation
    }, 1000)
share|improve this answer
Thas seems a quite troublesome if there would be many fields. Better to use some key action linked events. –  Johnny_D Jan 11 '13 at 9:55
Do not mention about exactly this code. I've just showed how to solve such problem –  CruorVult Jan 11 '13 at 10:01
add comment

Don't ever try to validate an email address with a regualr expression. You'll either end up allowing addresses which are not valid, or block email addresses which are perfectly valid and just annoy your visitors. It's also worth bearing in mind that the best regex so far for validating email addresses is this:


share|improve this answer
Woah, that's a huge one! –  Tondo Jan 11 '13 at 12:23
add comment

Your Answer


