使用jQuery移除Parsley的excluded属性无效,重绑验证失败求助
Hey there, let's work through this Parsley validation issue you're hitting. From what you described, the problem is that when you clear the input, the excluded attribute isn't being properly recognized by Parsley, or the validation isn't rebinding correctly. Here's how to fix it:
Key Issues to Address
First, Parsley caches element properties and validation rules when it's initialized. Just adding/removing the data-parsley-excluded attribute or toggling readonly won't automatically update the validation state—you need to explicitly tell Parsley to refresh or reinitialize.
Step-by-Step Solution
Let's adjust your existing logic to handle state changes properly, paired with Parsley's API methods:
Handle Input Value Changes
Attach aninputorchangeevent listener to your target input to detect when the user enters or clears a value:$('#your-input-id').on('input change', function() { const $input = $(this); const $form = $input.closest('form'); let parsleyInstance = $form.parsley(); // Case 1: Input has a valid value if ($input.val().trim() !== '') { // Set input to readonly and mark as excluded from validation $input.prop('readonly', true) .attr('data-parsley-excluded', 'true'); // Refresh Parsley to recognize the new excluded state if (parsleyInstance) { parsleyInstance.refresh(); } } // Case 2: Input is cleared else { // Remove readonly and excluded attributes $input.prop('readonly', false) .removeAttr('data-parsley-excluded'); // Destroy existing Parsley instance and reinitialize if (parsleyInstance) { parsleyInstance.destroy(); } // Re-run your initial validation setup handleValidation($form, yourTypeValue); } });Update Your
handleValidationFunction
Make sure your initial validation setup doesn't hardcode excluded states, and leaves room for dynamic updates:var handleValidation = function($form, type){ // Initialize Parsley with your base rules $form.parsley({ // Your existing validation config here errorClass: 'is-invalid', successClass: 'is-valid', // ... other options }); };
Critical Notes
- Use
parsley().refresh(): When you modify attributes on an already-validated field,refresh()tells Parsley to recheck the element's properties without full reinitialization. - Destroy & Reinitialize on Clear: For cases where removing
excludedisn't picked up byrefresh(), destroying the old Parsley instance and re-running your initial setup ensures all rules are reapplied correctly. - Double-Check Attribute Names: Ensure you're using
data-parsley-excluded(the correct Parsley data attribute) instead of justexcluded.
This should resolve the issue where cleared inputs weren't being reincluded in validation, and valid inputs stay excluded and readonly as expected.
内容的提问来源于stack exchange,提问作者acaputo

