jQuery Validation is a simple tools to validate a form with jQuery. We can custom error message location using this library. If you just want to set a box to gather all error messages, you can use this scheme.
Javascript
$('#form').validate({
rules: {
first: {
required: true
},
second: {
required: true
}
},
messages: {},
errorElement : 'div',
errorLabelContainer: '.errorTxt'
});
HTML
<form id="form" method="post" action="">
<input type="text" name="first" />
<input type="text" name="second" />
<div class="errorTxt"></div>
<input type="submit" class="button" value="Submit" />
</form>
But if you want to put error messages in different places for each fields, you can use this scheme.
Javascript
$('#form').validate({
rules: {
first: {
required: true
},
second: {
required: true
}
},
messages: {},
errorPlacement: function(error, element) {
var placement = $(element).data('error');
if (placement) {
$(placement).append(error)
} else {
error.insertAfter(element);
}
}
});
HTML
<form id="form" method="post" action="">
<input type="text" name="first" data-error="#errNm1" />
<input type="text" name="second" data-error="#errNm2" />
<div class="errorTxt">
<span id="errNm2"></span>
<span id="errNm1"></span>
</div>
<input type="submit" class="button" value="Submit" />
</form>
Comments
Post a Comment