How to validate dynamically generated input fields with jQuery Validation plugin ??
As we know jQuery validation plugin is the most commonly used client side form validation library which provides plenty of customization with an ease to save time for manually validating each HTML form elements from scratch.
Though this plugin provides lots of inbuilt function to customize validation, sometimes it becomes tricky to properly use this plugin as per our requirements.
For example in one of my recent project I was in a need to validate dynamically generated fields.
With some research, I came up with a solution which I’m describing below with an example.
Suppose we have a form to enter multiple records of people with name and email fields
To generate the above form the HTML code will be
1 2 3 4 5 6 |
<form id="add_people_form"> <input type="hidden" id="counter" value="1"> <button type="button" id="add_fields">+</button> <div id="add_people_div"></div> <button type="submit">Submit</button> </form> |
The Javascript will be
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
$(document).ready( function(){ $('#add_fields').click( function(){ add_inputs() }); $(document).on('click', '.remove_fields', function() { $(this).closest('.record').remove(); }); function add_inputs(){ var counter = parseInt($('#counter').val()); var html = '<div class="record"><input type="text" placeholder="Name" name="name_' + counter + '" class="name_input"><input type="email" name="email_' + counter + '" placeholder="Email" class="email_input"><button type="button" class="remove_fields">-</button></div>'; $('#add_people_div').append(html); $('#counter').val( counter + 1 ); } }); |
Now to validate the dynamically generated input fields
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
$('form#add_people_form').on('submit', function(event) { //Add validation rule for dynamically generated name fields $('.name_input').each(function() { $(this).rules("add", { required: true, messages: { required: "Name is required", } }); }); //Add validation rule for dynamically generated email fields $('.email_input').each(function() { $(this).rules("add", { required: true, email: true, messages: { required: "Email is required", email: "Invalid email", } }); }); }); $("#add_people_form").validate(); |
In below image, we can see each dynamically generated field are validated separately.
1 Comment
thx
2017-10-19 19:01:06