I'm having some trouble trying to figure out how to change the required message for some fields in my form. I have created a form where users can add or remove fields at their will.
So I have something like this:
div class="group">
<h3>Sexe</h3>
<label class="radio-label"><input type="radio" name="enfants[<?php echo $i; ?>][sexe]" value="Garçon" class="required" /><span class="text">Garçon</span></label>
<label class="radio-label"><input type="radio" name="enfants[<?php echo $i; ?>][sexe]" value="Fille" class="required" /><span class="text">Fille</span></label>
</div>
As you can see, I have a dynamic number created via php (if js is disabled). If enabled, the user adds fields and it generates a random number for it. Everything works at this point.
This is the code for validation:
form.validate({
rules: {
parent_telephone_maison: {
require_from_group: [1, ".phone-group"]
},
parent_telephone_cell: {
require_from_group: [1, ".phone-group"]
},
parent_telephone_travail: {
require_from_group: [1, ".phone-group"]
},
autre_telephone_maison: {
require_from_group: [1, ".autre-group"]
},
autre_telephone_cell: {
require_from_group: [1, ".autre-group"]
},
autre_telephone_travail: {
require_from_group: [1, ".autre-group"]
}
},
errorPlacement:
function(error, element) {
var id = element[0]['id'];
if (element.attr('type') === 'radio') {
var group = $(element).closest('.group');
var textarea = group.find('textarea').closest('[data-rel]');
if (textarea.length >= 1) {
textarea.before("<label for='"+id+"' class='error'>You need to choose an option.</label>");
} else {
group.append( "<label for='"+id+"' class='error'>You need to choose an option.</label>" );
}
}
}
});
As you can notice, I have tried to use the errorPlacement method to achieve what I needed. It worked, but each time I click on a radio button, the error is duplicating.
Is there a way to code this with the messages method? To be honest, I am not quite sure how to write it down.
I hope this is clear, I can provide more information if needed. And as always, thanks for your help.
errorPlacement
does what it says, it places the error. In other words, it puts the error into your layout. Once placed into the layout, the plugin will automatically toggle it. By using theappend
method, you are causing the duplication yourself. – Sparky Aug 15 '14 at 15:34error
object already contains the<label>
tags so you don't need to create these either. You also should not be specifying the actual error message in here. The error message is passed into this function from elsewhere. Use themessages
option to set custom error messages. – Sparky Aug 15 '14 at 15:36groups
option was created to deal with the issue of having the same message repeated on every field when using therequire_from_group
rule. – Sparky Aug 15 '14 at 15:39messages
option. It's very straightforward; what have you tried? – Sparky Aug 15 '14 at 19:55