This looks very simply, but I can't figure it out. I'm using the jquery validate plugin. I'm trying to validate <input name=first>
and <input name=second>
to output the error messages into:
<span id="errNm2"></span> <span id="errNm1"></span>
I already started writing the errorPlacement: which is where you customize your error message location.
How can I put the errors message in those <span>
?
$(document).ready(function () {
$('#form').validate({
errorPlacement: function(error, element) {
error.append($('.errorTxt span'));
},
rules,
});
<input type="text" name="first"/>
<input type="text" name="second"/>
<div class="errorTxt">
<span id="errNm2"></span>
<span id="errNm1"></span>
</div>
What you should use is the errorLabelContainer
jQuery(function($) {
var validator = $('#form').validate({
rules: {
first: {
required: true
},
second: {
required: true
}
},
messages: {},
errorElement : 'div',
errorLabelContainer: '.errorTxt'
});
});
.errorTxt{
border: 1px solid red;
min-height: 20px;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>
<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>
If you want to retain your structure then
jQuery(function($) {
var validator = $('#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);
}
}
});
});
#errNm1 {
border: 1px solid red;
}
#errNm2 {
border: 1px solid green;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>
<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>