1

我想创建一个包含验证错误的图层,并将其显示为与我的表单并排的工具提示。类似于以下示例:

+-------------+
|             |
|             |    Normal Form
|             |
+-------------+

+-------------+-----+
|             |     |
|             |-----+    Form with visible 
|             |          validation errors
+-------------+

清楚吗?错误容器只有在存在验证错误时才可见,并且应该位于表单本身的右上角区域。

实际上我有以下示例标记:

<form id="information" method="post" action="#">
   <fieldset>
      <legend>Please enter your contact details</legend>
          <div id="id">
              <label for="name">Name: (*)</label>
              <input type="text" id="name" class="details" name="name" maxlength="50" title="Insert your Name" />
          </div>
          <div id="id">
              <label for="email">Email: (*)</label>
              <input type="text" id="email" class="details" name="email" maxlength="50" title="Insert your Email" />
          </div>
   </fieldset>
   <div id="submission">
       <input type="submit" id="submit" value="Send" name="send"/>
   </div>
</form>

而这个jQuery代码:

$(document).ready(function () {
    var form = $('#information');
    var container = $('<div class="error"><p>Errors:</p><ol></ol></div>').appendTo(form).hide();
    var validator = form.validate({
        errorContainer: container,
        errorLabelContainer: $("ol", container),
        wrapper: 'li',
        meta: "validate"
    });
});

在表单下方附加错误列表非常有效。如何在表单顶部显示错误 div?

感谢您的帮助

4

1 回答 1

1

通过使用 ID 显式设置错误消息容器并设置标签容器,根据需要设置错误消息框的样式要容易得多。

<div id="formColumn">
    <form id="information" method="post" action="#">
   <fieldset>
      <legend>Please enter your details</legend>
          <div id="id">
              <label for="name">Name: (*)</label>
              <input type="text" id="name" class="details required" name="name" maxlength="50" title="Insert your Name" />
          </div>
          <div id="id">
              <label for="email">Email: (*)</label>
              <input type="text" id="email" class="details required" name="email" maxlength="50" title="Insert your Email" />
          </div>
   </fieldset>
   <div id="submission">
       <input type="submit" id="submit" value="Send" name="send"/>
   </div>
</form>
</div>
<div id="messageBox"><p>Errors:</p><ol></ol></div>​

jQuery:

$(function() {
    var form = $('#information');
    var validator = form.validate({
        errorContainer: "#messageBox",
        errorLabelContainer: "#messageBox ol",
        wrapper: 'li',
        meta: "validate"
    });
});

CSS:

#formColumn{
    display:inline;
    float:left
}
#messageBox{
    display:none;
    float:left
}​

此外,请谨慎使用“错误”类作为您包含的错误消息,因为验证器插件在其他地方使用此名称。

http://jsfiddle.net/yvxRc/

于 2012-06-12T18:23:42.623 回答