I have created a custom js code that adds validation to postal code. I accessed the relevant fields and added conditions.
var postalCodeInputs = document.querySelectorAll('.wpf-postal-code-char-requirement');
for (var i = 0; i < postalCodeInputs.length; i++) {
postalCodeInputs[i].addEventListener('input', function() {
var maxLength = 5;
var input = this;
if (input.value.length > maxLength) {
input.value = input.value.slice(0, maxLength);
}
if (input.value.length < maxLength) {
// Create an error message element
var errorMessage = document.createElement('div');
errorMessage.className = 'ihc-register-notice error-postcode';
errorMessage.textContent = 'Postal code must be 5 characters long.';
// Find the target div with id 'ihc_reg_number_7248' and append the error message to it
var targetDiv = document.getElementsByClassName('ihc-form-create-edit')[0].children[7]
var errorexist = document.getElementsByClassName('error-postcode');
if(errorexist.length==0){
targetDiv.appendChild(errorMessage);
}
} else {
// If the input is valid, remove any existing error message
var existingErrorMessage = document.getElementsByClassName('error-postcode');
if (existingErrorMessage.length>0) {
existingErrorMessage[0].remove();
}
}
});
}
I also tried adding event listener of DOMContentLoaded
document.addEventListener('DOMContentLoaded', function() {
// The same code as above
});
The issue is, when I run the above code in browser directly (by adding in console editor), it works fine. But when I add custom JS code to WPForms , it doesnot work.
