Getting Duplicate Error Messages with JQuery Validation Plugin
I'm a newbie to JQuery and the Validation plugin.
Short Description: I wanted all of my error messages to appear in one div at the top of the form, instead of next to each label. After a little head scratching and net searching, I came up with the following, which works, but the sourceurl: message comes up twice on the validation. I haven't a clue as to why. Any help would be appreciated. Cheers, John
Source Code:
<form name="siteauth" id="siteauth" action="savedata" type="POST">
<div class="message"></div>
<fieldset>
<label>Short Description:</label>
<br><input id="shortdescription" size="75" type="text" maxlength="50" name="shortdescription"/>
<br><label>Source URL:</label>
<br><input id ="sourceurl" size="75" type="text" maxlength="500" name="sourceurl"/>
<br><label>Callback URL:</label>
<br><input id="callbackurl" size="75" type="text" maxlength="500" name="callbackurl"/>
<br><label>Callback Content:</label>
<br><input id="in4" size="75" type="text" maxlength="100" name="callbackcontent"/>
<br>
<br><input type="submit" value="Add"/>
</fieldset>
</form>
<script src="htt开发者_开发技巧p://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#siteauth").validate({
rules: {
shortdescription: "required",
sourceurl: "required"
},
messages: {
shortdescription: "Enter a short description. ",
sourceurl: "Enter a Source URL. "
},
errorElement: "div",
wrapper: "div class=\"message\"",
errorPlacement: function (error, element){
error.appendTo($(".message"));
}
});
});
It's because you gave the class to the wrapper inside your error element as well, so this:
wrapper: "div class=\"message\"",
Should be just:
wrapper: "div",
Then it's not appending it to the top container and the elements it's creating inside there. You can give it a try here.
The above works, but a better solution is to use the intended property, errorLabelContainer
, which is also shown/hidden automatically i there are/aren't any errors, like this:
$(function(){
$("#siteauth").validate({
rules: {
shortdescription: "required",
sourceurl: "required"
},
messages: {
shortdescription: "Enter a short description. ",
sourceurl: "Enter a Source URL. "
},
errorElement: "div",
wrapper: "div",
errorLabelContainer: ".message"
});
});
Give that version a try here.
Instead of using the class use the ID attribute.
For example
<div class="message" id="errmsg"></div>
and change the Jquery line into
errorPlacement: function (error, element) { error.appendTo($("#errmsg"));
}
Live example Here
精彩评论