Reputation: 10699
I am having trouble editing the inserted HTML using the jQuery Validation plugin (version 1.12.0 with jQuery 1.9.1). I would like to add a Font Awesome icon inside the created error element. It would be before the error message, meaning a nice exclamation mark is shown before the message.
What I would like:
<input type="text" id="email" />
<span for="email" class="invalid">
<i class="fa fa-exclamation-circle"></i> This field is required.
</span>
What it would look like:
What I have so far:
$(".validate-form").validate({
errorClass: "invalid",
errorElement: "span"
});
I can actually achieve this by just editing the default messages to include the HTML, but it is sort of a hacky way to do it. This is what I am doing that is achieving the desired results:
jQuery.extend(jQuery.validator.messages, {
required: '<i class="fa fa-exclamation-circle"></i> ' + "This field is required."
});
I have also tried using the errorPlacement
callback, but had no luck. Does anyone know how I could achieve this?
Upvotes: 1
Views: 1052
Reputation: 98738
Your desired output:
<input type="text" id="email" />
<span for="email" class="invalid">
<i class="fa fa-exclamation-circle"></i> This field is required.
</span>
First thing wrong is that your input
is missing the name
attribute. The name
attribute is mandatory for this plugin. Also, AFAIK, you cannot use the for
attribute with anything but a label
. The message itself will be inside a label
container unless you change it with errorElement: "span"
.
<input type="text" name="email" id="email" />
<span class="invalid">
<i class="fa fa-exclamation-circle"></i><span>This field is required.</span>
</span>
Create your desired HTML markup and set it to display: none
. Use CSS to insert some space before the error message.
<input type="text" name="email" id="email" />
<span class="invalid" style="display: none;">
<i class="fa fa-exclamation-circle"></i>
</span>
Then try something like this...
errorClass: 'invalid', // default "error"
errorElement: 'span', // default "label"
errorPlacement: function(error, element) {
error.insertAfter(element.next('span').children());
},
highlight: function (element) {
$(element).next('span').show();
},
unhighlight: function (element) {
$(element).next('span').hide();
}
Upvotes: 4