且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery表单验证 - 如何迭代

更新时间:2023-12-03 15:52:10

为什么循环?为什么在循环内设置 blur()事件呢?我不明白你背后的理由。您可以只为您的字段指定一个类,为该类分配事件。

Why the for loop? And why set the blur() event inside of the loop like that?. I don't understand your reasoning behind this. Instead of creating an array of ids, you can just give your fields a class an assign the event on that class.

$('.field').blur(function () {
    alert(this.id);
});

编辑:
想法是使用对象而不是数组,基本上创建一个对象所有正则表达式和错误以及一个评估字段的函数。这样的事情:

The idea is to use objects instead of arrays and basically create one object with all the regex and errors and one function to evaluate the fields. Something like this:

var filters = {
    name : {
        re : /^[a-zA-Z]+([\s][a-zA-Z]+)*$/,
        error : 'Name Error!'
    },
    email : {
        re : /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/,
        error : 'E-Mail Error!'
    },
    password : {
        re : /^[a-zA-Z0-9]+([\_]?[\-]?[a-zA-Z0-9]+)*$/,
        error : 'Password Error!'
    }
};

var validate = function(klass, str) {
    var valid = true,
        error = '';
    for (var f in filters) {
        var re = new RegExp(f);
        if (re.test(klass)) {
            if (str && !filters[f].re.test(str)) {
                error = filters[f].error;
                valid = false;
            }
            break;
        }
    }
    return {
        error: error,
        valid: valid
    }
};

$('.field').blur(function() {
    var test = validate(
        $(this).attr('class'),
        $(this).val()
    );
    if (!test.valid) {
        $('#errors').append('<p>' + test.error + '</p>');
    }
});