I want to validate some fields passing a different pattern to a validation function.
send.addEventListener("click", function (event) {
let pattern = /^[A-Za-zÁ-Úá-ú\s]{3,15}$/;
let nameIsVal = regexValidator(pattern);
if (nameIsVal) {
return true;
} else {
event.preventDefault();
return false;
}
});
function regexValidator(pattern) {
if (!pattern.test(this.value)) {
return false;
} else {
return true;
}
}
I am assuming that you are in a class. Make sure that the this keyword points to the correct instance in your event handler, either with the .bind() keyword or with an arrow function.
I would register the handler like this:
send.addEventListener('click', (event) => this.checkRegex(event));
Or if your environment doesn't support arrow functions, this should work as well:
send.addEventListener('click', this.checkRegex.bind(this, event));
Then I would add the methods to the class like this:
checkRegex(event) {
let pattern = /^[A-Za-zÁ-Úá-ú\s]{3,15}$/;
let nameIsVal = this.regexValidator(pattern);
if (nameIsVal) {
return true;
} else {
event.preventDefault();
return false;
}
}
regexValidator(pattern) {
if (!pattern.test(this.value)) {
return false;
} else {
return true;
}
}