自定义html里面的jquery的errorElementvalidation

我将我的错误消息放在div (errorElement)中并给它errorClass:"callout border-callout error ,我需要自定义样式。这就是它现在的样子:

  
Here is my error message

但是我想在这个errorElement两个元素,所以我可以正确设置它。 理想情况下,它应如下所示:

  
Here is my error message

我当前的jqueryvalidation代码:

 $(function() { $('#form1').validate({ rules: { email: { required: true, email: true }, fname: { required: true, }, lname: { required: true, } }, messages: { email: { required: 'Please enter your email', email: 'Please enter a valid email' }, fname: { required: 'Please enter your First Name', }, lname: { required: 'Please enter your Last Name', } }, submitHandler: function(form) { $(form).ajaxSubmit({ dataType: 'json', success: function(jsonResponse) { //Example json object returned by server: [false, "You have already subscribed!"] var notyType; if (jsonResponse.response) { notyType = 'success'; } else { notyType = 'error'; } showNoty(jsonResponse.message, notyType); } }); }, errorClass: "error callout border-callout", }); }); 

更新:

 

您的代码有几个问题需要纠正…

1)修复HTML。 你有不匹配的div标签……具体来说,你还有一个不是

。 我没有看到任何其他HTML问题,但您的布局看起来像div元素的不寻常混合, input元素嵌套在span元素中。 如果你想让那些span元素表现得像行,那么恕我直言,它们应该是div元素。

2)错误类border-callout是一个真正的问题。 虽然技术上可以使class名包含连字符,但这是不好的做法。 为什么? 因为JavaScript会将该连字符解释为减号。 您在jsFiddle中未经编辑的代码显示错误消息将相互堆叠而不是切换。 只需从errorClass删除border-callout ,就可以清除该问题 。


至于您要问的是什么…如何将错误消息插入到充满其他HTML的预定义div中。

首先,你将不得不将消息放入自己的某种容器中…… labelpspan等。这是插件需要它的方式,因此它可以被定位。 除非您使用errorElement选项指定它,否则插件将默认使用label

 

然后使用errorPlacement回调函数和一堆jQuery DOM遍历方法将消息标签对象放在

 errorPlacement: function(error, element) { error.insertBefore(element.parent().next('div').children().first()); } 

分解:

  error // the error object (includes message and its label container) .insertBefore( // insert the error object before what's defined inside () element // your input element object .parent() // the span which encloses your input element .next('div') // the div which immediately follows your span .children() // everything inside your div .first() // the first element inside your div ) // closes insertBefore() 

然后,由于您还需要切换

容器以及错误消息,您需要使用highlightunhighlight回调函数以及一些jQuery DOM遍历方法…

 highlight: function (element) { $(element).parent().next('div').show(); }, unhighlight: function (element) { $(element).parent().next('div').hide(); } 

工作演示: http : //jsfiddle.net/naa6w/