动态生成元素的表单验证失效求助——技能添加更多功能场景
skills[] Fields Hey there! I totally get why this is tripping you up—jQuery Validate doesn't automatically apply rules to elements that get added to the DOM after the validator is initialized. Let's walk through how to fix this so every dynamic skill input triggers the required validation.
Why the Original Code Isn't Working
When you initialize $("#myform").validate(), the plugin only scans and binds rules to elements that exist in the DOM at that moment. Any new skills[] inputs you add later with your Add more click handler don't get included in those initial bindings, so the required check never runs on them.
Solution 1: Manually Add Rules to New Elements
This approach involves explicitly attaching the validation rule to each new input right after you add it to the DOM:
First, update your HTML to add a reusable class to the skill inputs (this helps with targeting):
<form id="myform"> <a id="add_more">Add more</a> <div id="skills_wrap"> <input type="text" name="skills[]" class="skill-input"> </div> <input type="submit" name="submit"> </form>
Then modify your script to add the validation rule to each new input:
<script> // Initialize the validator first $("#myform").validate({ rules:{ "skills[]": { required: true } }, messages: { "skills[]": { required: "Please enter a skill" } // Optional custom error message } }); // Handle "Add more" click $(document).on("click","#add_more",function(){ // Create the new input element const newSkillInput = $('<input type="text" name="skills[]" class="skill-input">'); $("#skills_wrap").append(newSkillInput); // Attach the required validation rule to the new input newSkillInput.rules("add", { required: true, messages: { required: "Please enter a skill" } }); }); </script>
Solution 2: Use Class-Based Rules (Cleaner, Scalable Approach)
If you prefer a more streamlined solution, define a validation rule for a CSS class, then apply that class to all skill inputs (both initial and dynamic):
<script> // Define a class rule for skill inputs $.validator.addClassRules("skill-input", { required: true, messages: { required: "Please enter a skill" } }); // Initialize the validator—no need to specify rules for "skills[]" here $("#myform").validate(); // Handle "Add more" click $(document).on("click","#add_more",function(){ $("#skills_wrap").append('<input type="text" name="skills[]" class="skill-input">'); }); </script>
This works because jQuery Validate automatically applies class-based rules to any element with the skill-input class, even if it's added dynamically after the validator is initialized.
Quick Notes
- If you wanted to ensure at least one skill is filled out (instead of every input), you'd need a custom rule—but based on your original code, it looks like you want each skill input to be required.
- Double-check that you're loading the jQuery Validate plugin before your custom script—this is a common easy-to-miss step!
内容的提问来源于stack exchange,提问作者Hetal Chauhan

