如何在jQuery验证插件中避免指定highlight与unhighlight方法时的代码重复
highlight and unhighlight Methods Great question—duplicating logic between these two methods is a common annoyance when setting up jQuery Validate. Let's look at a couple of clean approaches to refactor your existing code and eliminate repetition.
1. Extract a Reusable Helper Function
The core logic in both methods is targeting the input element and its associated label, then modifying the invalid class. We can wrap this in a helper function that takes an action (like addClass or removeClass) as a parameter.
Here's how to refactor your code:
(function($) { 'use strict'; // Helper function to toggle invalid classes on element and its label function toggleInvalidState(element, action) { $(element)[action]('invalid'); $(element.form).find(`label[for=${element.id}]`)[action]('invalid'); } $('form[data-behavior="validate"]').validate({ errorElement: 'span', ignore: ':hidden, .select-dropdown', normalizer: function(value) { if (!value) value = ''; if ($(this).is('[data-currency-mask]')) { return value.replace(/\$/g, '').replace(/,/g, ''); } return value; }, highlight: function(element) { toggleInvalidState(element, 'addClass'); }, unhighlight: function(element) { toggleInvalidState(element, 'removeClass'); } // ... rest of your validation options }); })(jQuery);
This way, if you ever need to adjust which elements get the invalid class (or change the class name itself), you only have to update the helper function once instead of both methods.
2. Use toggleClass with a Condition (Alternative Approach)
If you prefer a more concise approach, you can use jQuery's toggleClass method, which accepts a boolean to determine whether to add or remove the class. Since highlight is called when validation fails and unhighlight when it passes, we can pass true or false directly:
(function($) { 'use strict'; function setInvalidState(element, isInvalid) { $(element).toggleClass('invalid', isInvalid); $(element.form).find(`label[for=${element.id}]`).toggleClass('invalid', isInvalid); } $('form[data-behavior="validate"]').validate({ errorElement: 'span', ignore: ':hidden, .select-dropdown', normalizer: function(value) { if (!value) value = ''; if ($(this).is('[data-currency-mask]')) { return value.replace(/\$/g, '').replace(/,/g, ''); } return value; }, highlight: function(element) { setInvalidState(element, true); }, unhighlight: function(element) { setInvalidState(element, false); } // ... rest of your validation options }); })(jQuery);
This is slightly cleaner and makes the intent of each method even clearer—we're explicitly setting whether the element is in an invalid state.
Both approaches eliminate code duplication, make your code easier to maintain, and keep the logic DRY (Don't Repeat Yourself). Pick whichever fits your coding style better!
内容的提问来源于stack exchange,提问作者Kurt Peek

