使用选择的插件的JQuery验证表单进行Bootstrap 3验证状态 [英] Bootstrap 3 validation states with JQuery-validated form that uses Chosen plugin

查看:101
本文介绍了使用选择的插件的JQuery验证表单进行Bootstrap 3验证状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文

  • 我有一个正在使用 JQuery验证插件进行验证的表单.
  • 除文本区域外,所有表单控件都是必需的.
  • 我正在使用Bootstrap 3验证状态来设置要验证的表单控件的样式.
  • 对于select控件,我使用的是 Chosen Select插件
  • I have a form that I'm validating using JQuery Validate Plugin.
  • All form controls are required except for the textarea.
  • I'm using Bootstrap 3 validation states to style the form controls being validated.
  • For the select control, I'm using the Chosen Select Plugin

问题

我在弄清楚如何解决以下问题时遇到了麻烦:

I'm having trouble figuring out how to address the following:

1-阻止textarea控件应用于成功验证状态,因为此表单控件是可选的,因此未得到验证.

1- Prevent the textarea control from being applied the success validation state since this form control is not being validated as it is optional.

(要在下面的JSFiddle中重现该问题,请单击带有空白表格的Submit按钮)

(To reproduce the problem in the JSFiddle below, click the Submit button with the empty form)

2-将错误验证状态应用于下拉列表的边框.现在,只有标签可以应用错误验证状态.

2- Apply the error validation state to the border of the dropdown list. Right now only the label gets the error validation state applied.

3-删除错误验证状态和错误消息,并在用户从下拉列表中选择一个选项时应用成功类.现在,错误消息和错误类仍然存在.

3 - Remove the error validation state and error message, and apply the success class when the user chooses an option from the dropdown list. Right now the error message and error class remain.

JSFiddle

我创建了 JSFiddle 来说明问题.

HTML

<div class="container" role="main">
    <!-- Contents of the popover associated with the task name text input -->
    <div id="namePopoverContent" class="hide">
        <ul>
            <li><small>...</small></li>
            <li><small>...</small></li>
        </ul>
    </div>

    <form class="form-horizontal" method="post" action="" id="taskForm">
        <div class="row">
            <div class="col-md-9">
                <div class="form-group">
                    <label for="taskName" class="control-label col-md-1">Name</label>
                    <div class="col-md-11">
                        <input type="text" class="form-control taskNameValidation" id="taskName" name="taskName" autofocus required data-toggle="popover">
                    </div>
                </div>
            </div>
            <div class="col-md-3"></div>
        </div>

        <div class="row">
            <div class="col-md-9">
                <div class="form-group">
                    <label for="taskDataset" class="col-md-1 control-label">Dataset</label>
                    <div class="col-md-11">
                        <select class="form-control chosen-select taskDatasetValidation" data-placeholder="Choose a dataset" name="taskDataset" id="taskDataset" required>
                            <option value=""></option>
                            <option value="runnableDataset_Id1">Dataset 1</option>
                            <option value="runnableDataset_Id2">Dataset 2</option>
                            <option value="runnableDataset_Id3">Dataset 3</option>
                            <option value="runnableDataset_Id4">Dataset 4</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-md-3"></div>
        </div>
        <div class="row">
            <div class="col-md-9">
                <div class="form-group">
                    <label for="taskDescription" class="col-md-1 control-label">Description</label>
                    <div class="col-md-11">
                        <textarea class="form-control" name="taskDescription" id="taskDescription" maxlength="1000" rows="4"></textarea>
                    </div>
                </div>
            </div>
            <div class="col-md-3"></div>
        </div>
        <div class="row">
            <div class="col-md-9">
                <div class="pull-right top-margin">
                    <input type="submit" class="btn btn-primary btn-sm" value="Submit" name="taskSetUpSubmit">
                </div>
            </div>
            <div class="col-md-3"></div>
        </div>
    </form>

JS

//Bootstrap popover
$('[data-toggle="popover"]').popover({ 
    trigger: "hover focus",
    container: "body",
    placement: "bottom",
    html: true,
    title: "Name Tips",
    content: function() { return $('#namePopoverContent').html();}
});

//Chosen select plugin
$(function() {
    $('.chosen-select').chosen();
    $('.chosen-select-deselect').chosen({ allow_single_deselect: true });
});

//JQuery validate plugin
$(function() {
    $.validator.setDefaults({
        errorClass: 'text-danger',
        ignore: ':hidden:not(.chosen-select)',
        errorPlacement: function (error, element) {
            if (element.hasClass('chosen-select'))
                error.insertAfter(element.siblings(".chosen-container"));
            else {
                error.insertAfter(element);
            }
        }
    });

    //rules and messages objects
    $("#taskForm").validate({
        highlight: function(element) {
            $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
        },
        unhighlight: function(element) {
            $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
        }
    });

    $('.taskNameValidation').each(function() {
        $(this).rules('add', {
            required: true,
            messages: {
                required: "Provide a space-separated name"
            }
        });
    });

    $('.taskDatasetValidation').each(function() {
        $(this).rules('add', {
            required: true,
            messages: {
                required: "Choose a dataset"
            }
        });
    });
});

我一直在为此而苦苦挣扎.任何帮助将不胜感激.

I've been struggling with this without any luck. Any help will be greatly appreciated.

推荐答案

防止textarea控件被应用到成功验证状态,因为此表单控件是可选的,因此未得到验证.

Prevent the textarea control from being applied the success validation state since this form control is not being validated as it is optional.

空的textarea是有效的",因为您的验证说空字段是有效的,因此为绿色.您可以有条件地使用highlightunhighlight,这样它就不会应用于您的textarea.但是,当评估您的maxlength规则时,它将不起作用. 我知道没有解决方法,当该字段在技术上为有效"但仍为空时,将导致unhighlight被忽略.此插件中没有提供可选"条件/状态...评估表单后,字段要么为有效",要么为无效",中间没有任何内容.

The empty textarea is "valid" because your validation says an empty field is valid, therefore it's green. You could conditionally use highlight and unhighlight so that it will not be applied to your textarea. However, then it will not work when your maxlength rule is evaluated. I know of no workaround that will cause unhighlight to get ignored when the field is technically "valid" and yet still empty. There is no "optional" condition/state provided in this plugin... once the form is evaluated, fields are either "valid" or "invalid", nothing in between.

编辑:您可以使用自定义的:blank选择器,将类highlightunhighlight有条件地应用于textarea,并将类应用于此可选"元素.然后您仍然会得到红色&绿色轮廓,但仅当填写此可选"字段和/或评估您的规则时.

EDIT: You can conditionally apply highlight and unhighlight on the textarea using the custom :blank selector and applying a class to this "optional" element. Then you'll still get the red & green outlines, but only when this "optional" field is filled out and/or your rules are evaluated.

highlight: function (element) {
    if (! ($(element).hasClass('optional') && $(element).is(':blank'))) {
        $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    }
},
unhighlight: function (element) {
    if (! ($(element).hasClass('optional') && $(element).is(':blank'))) {
        $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
    }
}

  • 将错误验证状态应用于下拉列表的边框.现在,只有标签可以应用错误验证状态.

    Apply the error validation state to the border of the dropdown list. Right now only the label gets the error validation state applied.

    您需要查看呈现的DOM并找到动态创建的Chosen元素.然后,您需要编写jQuery来遍历此元素,并通过highlightunhighlight有条件地应用适当的类.

    You need to look at the rendered DOM and find the dynamically created Chosen element. Then you need to write jQuery to traverse over to this element and conditionally apply the appropriate classes via highlight and unhighlight.

    highlight: function (element) {
        if ($(element).hasClass('chosen-select')) {
            $(element).siblings('.chosen-container').removeClass('has-success').addClass('has-error');
        }
        $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    },
    unhighlight: function (element) {
       if ($(element).hasClass('chosen-select')) {
           $(element).siblings('.chosen-container').removeClass('has-error').addClass('has-success');
       } 
       $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
    }
    

    上方的这段代码是将has-errorhas-success类应用于呈现的选择的div元素;您只需要调整CSS,以便有一个红色边框.否则,就像在下面的演示中一样,为此编写自己的CSS类.进行相应的调整.

    This code above is applying the has-error and has-success classes to the rendered Chosen div element; you just need to adjust your CSS so that there is a red border. Otherwise, write your own CSS classes for this like I did in the demo below. Adjust accordingly.

    删除错误验证状态和错误消息,并在用户从下拉列表中选择一个选项时应用成功类.

    Remove the error validation state and error message, and apply the success class when the user chooses an option from the dropdown list.

    您必须编写一个change处理程序,该处理程序每​​次更改select元素时都会调用.valid()方法.这是因为您正在与呈现的选择列表进行交互,而不是与实际的select元素进行交互.否则,将无法正确触发jQuery Validate插件.

    You must write a change handler that calls the .valid() method on the select element every time it changes. This is because you are interacting with the rendered select list and not the actual select element. Otherwise, the jQuery Validate plugin is not properly triggered.

    $('.chosen-select').on('change', function () {
        $(this).valid();
    });
    

  • 演示: https://jsfiddle.net/jxvqsodz/7/

    DEMO: https://jsfiddle.net/jxvqsodz/7/

    这篇关于使用选择的插件的JQuery验证表单进行Bootstrap 3验证状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆