使用jQueryvalidation在单独的div中显示错误消息

我正在使用jQueryvalidation,我想在div中显示错误消息

在表单下方显示的默认值不适用于我的表单设计。

validation脚本链接到我有表单的页面,它看起来像:

  $(function validate() { var rules = { rules: { full_name: { minlength: 2, maxlength: 50, required: true }, address: { minlength: 5, required: true }, city: { minlength: 2, required: true }, state: { minlength: 2, maxlength: 2, required: true }, zip: { minlength:5, maxlength:5, required: true }, phone: { required: true, phoneUS: true }, phone_other: { required: true, phoneUS: true }, email: { required: true, email: true }, date_to_start: { required: true }, ssn: { required: true, ssn: true, }, salary: { required: true } } }; var validationObj = $.extend (rules, Application.validationRules); $('#employment-application').validate(validationObj); }); 

现在我尝试更改$('#employment-application').validate(validationObj); 对于下面的代码以及尝试将其添加到我打开表单的页面底部,两者都给出了负面结果。 该脚本似乎添加了style="display:none;"errorContainer并且不会在任何地方加载任何错误。

(尝试更改$('#employment-application').validate(validationObj);到下面)

 $("#employment-application").validate({ errorContainer: "#errorContainer", errorLabelContainer: "#errorContainer", errorElement: "li" }) 

所以重新上限,我想使用jQuery表单validation并显示在单独的div中收到的错误消息,因为默认设置不适用于我的表单设计。

您可以使用errorPlacement选项传递这样的回调: http : //jsfiddle.net/cMhQ7/

我使用了div id的标准,即输入元素的名称与_validate后缀连接,但您可以根据需要进行更改。

HTML

 

使用Javascript

 $(function validate() { var rules = { rules: { full_name: { minlength: 2, maxlength: 50, required: true }, }, errorPlacement: function (error, element) { var name = $(element).attr("name"); error.appendTo($("#" + name + "_validate")); }, }; $('#employment-application').validate(rules); }); 

如果只想将默认位置更改为某些元素,则可以使用此改进。 这实现了validation脚本的默认行为

  errorPlacement: function(error, element){ var name = $(element).attr("name"); var $obj = $("#" + name + "_validate"); if($obj.length){ error.appendTo($obj); } else { error.insertAfter(element); } },