| 1 |
export function validate(ref, validations, errorMessages = {}) { |
| 2 |
let isValid = true; |
| 3 |
// Clear previous errors |
| 4 |
clearValidationError(ref); |
| 5 |
|
| 6 |
const value = ref.value.trim(); |
| 7 |
|
| 8 |
// Perform validations |
| 9 |
validations.forEach((validation) => { |
| 10 |
if (validation === 'required' && value === '') { |
| 11 |
isValid = false; |
| 12 |
setValidationError(ref, errorMessages.required || 'This field is required.'); |
| 13 |
} |
| 14 |
if (isValid && validation.startsWith('startsWith') && !value.startsWith(validation.split(':')[1])) { |
| 15 |
isValid = false; |
| 16 |
setValidationError(ref, errorMessages.startsWith || 'This field must start with http'); |
| 17 |
} |
| 18 |
}); |
| 19 |
|
| 20 |
return isValid; |
| 21 |
} |
| 22 |
|
| 23 |
// Helper function to clear previous errors |
| 24 |
function clearValidationError(ref) { |
| 25 |
ref?.classList.remove('woo-mailerlite-input-error'); |
| 26 |
|
| 27 |
const errorElement = ref?.nextElementSibling; |
| 28 |
if (errorElement && errorElement.classList.contains('woo-mailerlite-error-message')) { |
| 29 |
errorElement.remove(); |
| 30 |
} |
| 31 |
if (ref.classList.contains('select2-hidden-accessible')) { |
| 32 |
ref.nextSibling.classList.remove('woo-mailerlite-input-error'); |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
// Helper function to set validation error |
| 37 |
function setValidationError(ref, message) { |
| 38 |
|
| 39 |
ref.classList.add('woo-mailerlite-input-error'); |
| 40 |
// if (ref.classlist) |
| 41 |
|
| 42 |
const errorElement = document.createElement('span'); |
| 43 |
errorElement.classList.add('woo-mailerlite-error-message'); |
| 44 |
|
| 45 |
errorElement.style.color = 'red'; |
| 46 |
// errorElement.style.position = 'absolute'; |
| 47 |
errorElement.style.top = '100%'; |
| 48 |
errorElement.textContent = message; |
| 49 |
if (ref.classList.contains('select2-hidden-accessible') || ( ref.classList.length === 1)) { |
| 50 |
if (ref.nextSibling.type === 'span') { |
| 51 |
ref.nextSibling.classList.add('woo-mailerlite-input-error'); |
| 52 |
} |
| 53 |
errorElement.style.position = 'absolute'; |
| 54 |
ref.parentNode.after(errorElement); |
| 55 |
} |
| 56 |
|
| 57 |
ref.parentNode.insertBefore(errorElement, ref.nextSibling); |
| 58 |
|
| 59 |
} |
| 60 |
|
| 61 |
// Helper function to validate email |
| 62 |
function validateEmail(email) { |
| 63 |
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; |
| 64 |
return emailRegex.test(email); |
| 65 |
} |