使用jQuery检查多个输入的相同错误

时间:2014-12-19 18:43:51

标签: jquery

我正在尝试对keyup事件执行错误检查。我想避免为每个输入编写相同的代码。我做错了什么?

$(function(){

    var Regex     =  /^\s*[a-zA-Z0-9,\s]+\s*$/;
    var selector  = [$('#username'),$('#password')];
    var container = $('.error');

    $.each(selector).keyup(function() {
        if(selector.val().length<=4 || selector.val().length>10) {
            $(container).remove();
            $(this).after('<span class="'+container+'">"The '+selector+' must contain a minimum of 4 characters and a maximum of 10"</span>');
        } else if(!Regex.test(selector)) {
            $(container).remove();
            $(this).after('<span class="error '+container+'">"The '+selector+' must contain letters and numbers only"</span>');
        } else {
            $(this).after('<span class="good '+container+'">Looks good</span>');
        }
    });
});

更新 在对代码进行一些修改之后,这就是我得到的,并且它运行得很好:

$(function(){

var Regex     =  /^\s*[a-zA-Z0-9,\s]+\s*$/;
var container = $('.input-error');

$(".inputs").keyup(function(e){

        var input_content = $(this).val();
        var input_name    = $(this).attr("name");       

        if(input_content.length<=4 || input_content.length>10){

            $('.input-error').remove();
            $(this).after('<span class="error input-error">"The '+input_name+' must contain a minimum of 4 characters and a maximum of 10"</span>');

        }else if(!Regex.test(input_content)){

            $('.input-error').remove();
            $(this).after('<span class="error input-error">"The '+input_name+' must contain letters and numbers only"</span>');

        }else{
            $('.input-error').remove();
            $('.input-error').addClass("good");
            $(this).after('<span class="good input-error">"Looks Good"</span>');
        }

});
});

感谢您的帮助...

2 个答案:

答案 0 :(得分:0)

您可以在元素上使用公共类 - 因此您可以编写一个选择器:

<input type="text" class="required-input" />
<input type="text" class="required-input" />

JS:

var Regex     =  /^\s*[a-zA-Z0-9,\s]+\s*$/;
var errorClass = "error";

$(".required-input").keyup(function(e) {
    //$(this) refers to the element having the current keyup action

    if(this.value.length<=4 || this.value.length>10) {
        $(this).next("." + errorClass).remove();
        $(this).after('<span class="'+errorClass +'">"The input must contain a minimum of 4 characters and a maximum of 10"</span>');
    } else if(!Regex.test(this.value)) {
        $(this).next("." + errorClass).remove();
        $(this).after('<span class="error '+errorClass+'">"The input must contain letters and numbers only"</span>');
    } else {
        $(this).after('<span class="good ' + errorClass + '">Looks good</span>');
    }
});

答案 1 :(得分:0)

而不是像这样使用它

var selector  = [$('#username'),$('#password')];

只需为输入字段指定一个类并使用它:

   $('.inputclass').keyup(function() { 
        // ... code to execute comes here

这将使用类(在本例中为)inputclass。

来定位所有输入字段