基于formvalidation.io的动态校验规则:依全局变量启用notEmpty校验器
Got it, let's tackle this scenario without writing custom validators—here's a reusable global approach that works across multiple fields:
Step 1: Initialize Form with Disabled Default Validator
First, set up your form validation configuration, and disable the notEmpty validator for the email field by default. This way it only kicks in when your global variable meets the condition:
// Initialize form validation const formValidator = formValidation.formValidation( document.getElementById('your-form-element'), { fields: { email: { validators: { notEmpty: { enabled: false, // Start disabled message: 'Email is required' }, // Keep other validators (like email format check) active as needed emailAddress: { message: 'Please enter a valid email address' } } }, // Add other fields here with their base validator configs } } );
Step 2: Create a Global Control Function
Make a single function that checks your global variables and updates validator states across all relevant fields. This is where you centralize all your conditional logic—no need for scattered custom code:
function syncValidatorsWithGlobalVars() { // Check your global email requirement flag const shouldRequireEmail = window.emailrequired === 1; // Toggle the email field's notEmpty validator formValidator.enableFieldValidators('email', 'notEmpty', shouldRequireEmail); // Add more field controls here as needed // Example: For a phone field tied to another global variable // const shouldRequirePhone = window.phonerequired === 1; // formValidator.enableFieldValidators('phone', 'notEmpty', shouldRequirePhone); }
Step 3: Trigger the Sync at the Right Times
Call this function whenever your global variables might change, plus on page load to set the initial state:
// Run on page load to set initial validator states document.addEventListener('DOMContentLoaded', syncValidatorsWithGlobalVars); // If your global variable gets updated by user actions (like a toggle), call the function there too // Example: If a checkbox updates emailrequired document.getElementById('email-required-toggle').addEventListener('change', function() { window.emailrequired = this.checked ? 1 : 0; syncValidatorsWithGlobalVars(); });
How This Works
This leverages formvalidation.io's built-in enableFieldValidators method to toggle validator states dynamically. By centralizing all your conditional logic in one function, you have a scalable global solution—just add more field/validator pairs to the sync function whenever you need to handle new conditional requirements.
内容的提问来源于stack exchange,提问作者user1480192

