JQuery Validator:错误检查和消息管理

时间:2014-07-30 10:33:14

标签: javascript jquery html css html5

我已使用 JQuery Validation 插件实现了输入检查。

我的自定义配置如下:

$(document).ready(function() {
    var $validator = $("#commentForm").validate({
      rules: {
            serviceName: {
                minlength: 6
            }
        },
        errorPlacement: function (error, element) {
            $('#' + $(element).attr('id') + "-error").removeClass('hidden');
        }        
    });
}

然后,进入页面:

<form id="commentForm" method="get" action="" >
    <div class="inputs">
        <label for="nome-servizio">Nome del servizio</label>
        <div class="wizard-input-section input-group col-lg-8" style="margin-top: 0">
            <span class="input-group-addon"><i class="fa fa-cog"></i></span>
            <input type="text" class="form-control" id="serviceName" name="serviceName" placeholder="Es. pentaho-reply-server" data-serialize="1" required/>
        </div>

        <!-- Error alert -->
        <div class="alert alert-info alert-dismissable col-md-8 hidden" role="alert" id="serviceName-error">
            <button type="button" class="close" data-dismiss="alert">
                <span aria-hidden="true">&times;</span><span class="sr-only">Chiudi</span>
            </button>
            <p>
                <strong>Errore!</strong> Il nome del servizio deve:
                <ul>
                    <li>avere una lunghezza minima di 4 caratteri ed una massima di 10;</li>
                    <li>contenere solo caratteri alfanumerici, trattini ed underscore.</li>
                </ul>
            </p>
        </div>
    </div>
</form>

根据这些设置,当发生错误时,删除hidden类会显示错误提示。

case1

现在,我希望通过编写有效输入(再次添加hidden类)自动消失错误警告。

case2

所需

case3

如果可能,我该怎么做?

1 个答案:

答案 0 :(得分:1)

我通过使用高亮和非高亮功能找到了解决方案:

var $validator = $("#commentForm").validate({
  rules: {
        serviceName: {
            minlength: 6
        }
    },
    errorPlacement: function(error, element) {
    },
    highlight: function(element, errorClass, validClass) {
        $('#' + $(element).attr('id') + "-error").removeClass('hidden');
    },
    unhighlight: function(element, errorClass, validClass) {
        $('#' + $(element).attr('id') + "-error").addClass('hidden');
    }
});