/**
* Form Wrapper with Sanity Checks for Routine Automation
*
* Wraps existing form logic and adds basic validation.
*
* @param {object} form - The form object (e.g., from document.getElementById).
* @param {function} originalSubmit - The original submit handler.
* @param {object} validationRules - An object defining validation rules for each field.
* e.g., { fieldName: { type: 'required', pattern: /^\d+$/ } }
*/
function wrapForm(form, originalSubmit, validationRules) {
form.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent default form submission
let isValid = true;
// Validate each field based on the rules
for (const fieldName in validationRules) {
const rule = validationRules[fieldName];
const field = form.querySelector(`[name="${fieldName}"]`);
if (rule.type === 'required' && !field.value.trim()) {
console.error(`Field "${fieldName}" is required.`);
isValid = false;
field.classList.add('error'); // Add an error class for styling
}
if (rule.type === 'pattern' && field.value.trim() && !rule.pattern.test(field.value.trim())) {
console.error(`Field "${fieldName}" does not match the pattern.`);
isValid = false;
field.classList.add('error');
}
}
if (!isValid) {
// Display validation errors to the user (e.g., using a message)
const errorMessagesElement = document.getElementById('error-messages');
if (errorMessagesElement) {
errorMessagesElement.innerHTML = ''; // Clear previous errors
for (const fieldName in validationRules) {
const rule = validationRules[fieldName];
const field = form.querySelector(`[name="${fieldName}"]`);
if (field.classList.contains('error')) {
errorMessagesElement.innerHTML += `<p><strong>${fieldName}:</strong> ${rule.message || 'Invalid input'}</p>`;
}
}
}
return; // Stop submission if validation fails
}
// Call the original submit handler if validation passes
originalSubmit();
});
}
//Example Usage (assuming you have a form element with id "myForm")
// wrapForm(document.getElementById('myForm'), myOriginalSubmitHandler, myValidationRules);
/**
* Example validation rules. Customize this to match your form.
* @returns {object}
*/
function createValidationRules() {
return {
name: { type: 'required', message: 'Name is required' },
email: { type: 'required', pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ , message: 'Invalid email format' },
age: { type: 'required', pattern: /^\d+$/ , message: 'Age must be a number' }
};
}
Add your comment