jQuery&引导输入验证

时间:2016-12-03 17:39:40

标签: jquery html twitter-bootstrap validation

它看起来像什么:
input is wrong
应该是什么:
how it shoud be

出于某种原因,每次我在输入框中输入内容时,都会添加另一个错误字形。有人能帮助我吗?

HTML代码

<div class="row">
    <div class="col-xs-12 col-sm-6 col-md-6 col-lg-12">
        <div class="form-group has-feedback" id="num">
            <input type="text" required pattern="[a-z]{1}[0-9]{7}" name="studo_number" id="studo_number" class="form-control input-lg" placeholder="Student/docent nummer" tabindex="4" title="Het student/docent nummer moet beginnen met een kleine letter gevolgd door 7 cijfers." maxlength="8">
        </div>
    </div>
</div>

jQuery代码

jQuery(function () {
    $("#studo_number").keyup(function () {
        var VAL = this.value;

        var studo = new RegExp('[a-z]{1}[0-9]{7}');

        if (studo.test(VAL)) {
                if ($('#num').hasClass('has-error')){
                $(this).parent().removeClass('has-error');
            }
            $('#num').addClass('has-success');
            $(this).addClass('has-success');
            $(this).after('<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>');
        }
        else{
            $('#num').addClass('has-error');
            $(this).addClass('has-error');
            $(this).after('<span class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>');
        }
    });
});

1 个答案:

答案 0 :(得分:0)

问题出在keyup时,使用方法.after()创建新元素。

这样的一些事情会解决你的问题,我们会在执行之前检查一下我们尚未完成的事情:

jQuery(function () {
    $("#studo_number").keyup(function () {
        var VAL = this.value;

        var studo = new RegExp('[a-z]{1}[0-9]{7}');

        //Check if input is good and we not already pass in this part
        if (studo.test(VAL) && !$('#num').hasClass('has-success')) {
            //Remove if exist the span glyphicon-remove and the class has-error
            if ($('#num').hasClass('has-error')){
                $(this).parent().find('.glyphicon-remove').remove();
                $(this).parent().removeClass('has-error');
            }
            $('#num').addClass('has-success');
            $(this).addClass('has-success');
            $(this).after('<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>');
        } else if (!studo.test(VAL) && !$('#num').hasClass('has-error')) {
            //Remove if exist the span glyphicon-ok and the class has-success
            if ($('#num').hasClass('has-success')){
                $(this).parent().find('.glyphicon-ok').remove();
                $(this).parent().removeClass('has-success');
            }
            $('#num').addClass('has-error');
            $(this).addClass('has-error');
            $(this).after('<span class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>');
        }
    });
});