65.9K
CodeProject 正在变化。 阅读更多。
Home

jQuery 验证样式

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.75/5 (20投票s)

2012年6月25日

CPOL

2分钟阅读

viewsIcon

107617

downloadIcon

5353

这个应用程序允许用户以三种优雅的方式显示验证消息,例如内联、摘要和弹出窗口。

介绍 

这个应用程序借助 jQuery 插件进行简单的客户端表单验证。在这里,我想展示 jQuery 的不同验证样式以及基本的 HTML 和 jQuery 示例。


我在 http://saffroze.com/jquery-validation-styles/ 上发表了一篇文章

背景  

ASP.NET MVC 3 使用 jQuery 验证进行表单验证,jQuery 验证库具有远程验证功能,使用 ASP.NET MVC 库使用此功能非常容易,您可以在 http://docs.jquery.com/Plugins/validation 上找到更多信息。

  • 每个验证属性都有一个 ToJson 方法,它将属性序列化为字典
    $("#form").validate({
     
    rules: {
     
    firstname: { required: true, minlength: 5, maxlength: 10 },
     
    lastname: { required: true, minlength: 5, maxlength: 10 },
     
    email: { required: true, email: true },
     
    mobile: { required: true, digits: true, minlength: 10, maxlength: 10 }
     
    }
     
    });
  • 所有错误标签都显示在一个 ID 为“validationSummary”的无序列表中,作为错误消息的附加容器。当发生错误时,作为“errorContainer”给出的元素都会显示和隐藏。
    errorContainer: "#validationSummary"
  • 错误标签本身被添加到作为 errorLabelContainer 给出的元素中,这里是一个无序列表。
    errorLabelContainer: "#validationSummary ul"
  • 因此,错误标签也被包装在 li 元素中(wrapper 选项)。
    wrapper: “li”
  • 一个自定义消息显示处理程序。将错误映射作为第一个参数,将错误数组作为第二个参数,在验证器对象的上下文中调用。
    showErrors: function (errorMap, errorList) {
    .
    .
    .
    } 

实现 

    这段代码演示了一个基本的 jQuery 验证示例,jQuery Validate 插件在表单提交之前验证表单,如果表单有效则提交表单,否则表单不会被提交。

  1. 在您的页面中包含 jQuery 插件和验证脚本。

    <script type="text/javascript" src="../../Scripts/jquery.validate.js">&lt;/script>
    
        &lt;script type="text/javascript" src="../../Scripts/jquery-ui-1.8.11.js">&lt;/script> 
  2. 在您的页面中添加以下脚本。它非常详细,因此无需解释每一行。
        $(document).ready(function () {
            //Set border color when text class getting focus or remove border color when lost focus from textbox.
            $('.text')
            .focus(function () { $('.text').removeClass('focused'); $(this).addClass('focused'); })
            .blur(function () { $(this).removeClass('focused'); });
     
            //Fire validation events
            $("#form").validate({
     
                //Setting validation type like, Required, Minimum or Maximum Length, Data Type etc.
                rules: {
                    firstname: { required: true, minlength: 5, maxlength: 10 },
                    lastname: { required: true, minlength: 5, maxlength: 10 },
                    email: { required: true, email: true },
                    mobile: { required: true, digits: true, minlength: 10, maxlength: 10 }
                },
     
                //All error labels are displayed inside an unordered list with the ID "validationSummary"
                //Additonal container for error messages. The elements given as the "errorContainer" are all shown and hidden when errors occur.
                errorContainer: "#validationSummary",
     
                //But the error labels themselve are added to the element(s) given as errorLabelContainer, here an unordered list.
                errorLabelContainer: "#validationSummary ul",
     
                //Therefore the error labels are also wrapped into li elements (wrapper option).
                wrapper: "li",
     
                //A custom message display handler. Gets the map of errors as the first argument and and array of errors as the second, 
                //called in the context of the validator object.
                showErrors: function (errorMap, errorList) {
                    $('.errorList').hide();
                    $('.inlineMessage').hide();
                    $('#validationSummary').hide();
                    var messages = "";
                    $.each(errorList, function (index, value) {
                        var id = $(value.element).attr('id');
                        messages += "<span>" + (index + 1) + ". <a title='click to view field' href='javascript:setFocus(" + id + ");'>[" + $(value.element).attr('name') + "]</a> " + value.message + "</span>
    ";
                    });
                    messages = "
     
     
    <div class='errorWrapper'>
     
     
    <h1>Please correct following errors:</h1>
     
    " + messages + "</div>
     
    ";
                    switch ($('input[name=DisplayType]:checked', '#form').val()) {
                        case "Popup":
     
                            //Showing validation summary in Popup window
                            $('#dialog-validation').html(messages);
                            $('#dialog-validation').dialog('open');
                            break;
                        case "Summary List":
     
                            //Showing validation summary in list of the same page
                            $('#summary-validation').html(messages);
                            $('#summary-validation').show("fast");
                            break;
                        case "Inline":
     
                            //Showing validation in inline format
                            $.each(errorList, function (index, item) {
                                $(item.element).next('div').html("<span style='font-weight:bold'>[" + $(item.element).attr('name') + "]</span> " + item.message);
                                $(item.element).next('div').show("fast");
                            });
                            break;
                    }
                },
     
                //If all validations are successfully validate then execute submitHandler function
                submitHandler: function () {
                    $('#summary-validation').empty();
                    $('#dialog-validation').empty();
                    alert("All fields are valid!")
                }
            })
     
            //jQuery Modal Dialog boxes can also use to display list of validation erorrs.
            $("#dialog-validation").dialog({
                resizable: false,
                height: 190,
                width: 350,
                modal: true,
                autoOpen: false,
                title: "Validation Errors",
                buttons: {
                    "Ok": function () {
                        $(this).dialog("close");
                        $('.focused').focus();
                    }
                }
            });
        });
     
        //If validation errors are occured in any field, it will display field name with link, clicking on link it will set focus of perticular field.
        function setFocus(ele) {
            $(ele).focus();
        }
    
  3. HTML 页面
    1. 如果您需要将验证显示在字段附近,则必须添加带有类名为“inlineMessage”的“”
      <div class="formWrapper" id="formStyle"><form id="form" action="" method="post" name="form"><label>First Name</label> <input id="firstname" class="text" type="text" name="firstname" />
      <div class="inlineMessage"></div> </form>
      </div>
    2. 用于错误消息的隐藏容器
      <div id="validationSummary">
             	<ul class="errorMessageList">
      	       </ul>
          	</div>
      
    3. 在同一页面中显示验证摘要
      <div style="display: none;" id="summary-validation" class="errorList">
      	    </div>
      
    4. 在模态对话框中显示验证摘要。
      <div style="display: none;" id="dialog-validation" class="errorList">
        </div>
      
    5. 为表单、输入框、按钮、对话框和验证消息添加样式。请访问 Views/Shared/_Layout.cshtml

您的想法

如果您发现其中存在问题或错误,请留下评论或给我发送电子邮件。如果您对此有任何说明,也请告诉我,这样我就不必重做您的辛勤工作。如果您觉得这有帮助,请提供一个 “投票”
© . All rights reserved.