如何使用jQuery Validate验证DataTables表格是否为空
Solution: Validate DataTables Isn't Empty on Form Submit
Got it, let's get this sorted for you! You already have jQuery Validate handling your input's required validation, and adding the DataTables empty check is straightforward. Here's a complete implementation that fits right into your existing code:
Updated HTML
We'll add a hidden error message container right above the table to display our validation warning:
<form method="post" id="form"> <input type="text" id="txt" required> <!-- Hidden error message for table validation --> <div id="table-error" class="error" style="color: red; display: none;"> Please add at least one entry to the table before submitting. </div> <table id="table"> <thead> <tr> <th>No.</th> <th>Name</th> <th>Address</th> </tr> </thead> </table> <button id="button" type="submit">Save</button> </form>
Modified jQuery Code
We'll extend your existing validation logic to check the DataTable's content, plus add a little extra to hide the error automatically when rows are added:
$(document).ready(function () { var grid = $('#table').DataTable(); // Remove this line if you want the table to start empty grid.row.add([ '1', 'Jake', 'England' ]).draw(false); // Hide error on load if table has data if (grid.data().any()) { $('#table-error').hide(); } $("#form").validate({ submitHandler: function (form) { // Check if the DataTable has any rows if (!grid.data().any()) { // Show the error message and stop form submission $('#table-error').show(); return false; } else { // Hide the error if it was visible, then submit the form $('#table-error').hide(); form.submit(); } } }); // Optional: Auto-hide error when rows are added/removed $('#table').on('draw.dt', function() { if (grid.data().any()) { $('#table-error').hide(); } }); });
Breakdown of Key Changes:
- Error Message: The hidden
divgives us a clean place to show the table empty warning. Style it to match your form's existing error styling (I added basic red text for example). - Empty Check:
grid.data().any()is exactly the method you mentioned—it returnstrueif there's at least one row. We use!grid.data().any()to catch the empty table case. - Validation Flow: In the
submitHandler, we first check the table. If it's empty, we show the error and returnfalseto block submission. If not, we proceed with the form submit. - Auto-Hide Error: The
draw.dtevent listens for DataTables updates (like adding/removing rows) and hides the error automatically once the table has data—no need for users to click submit again to make it disappear.
Quick Notes:
- If you want the table to start empty, just delete the
grid.row.add(...)test line. - Tweak the error message text and styling to fit your app's design.
内容的提问来源于stack exchange,提问作者Stfvns
相关产品推荐
相关产品推荐

