I have just worked on a basic javascript file to parse html form data on the front-end before it gets submitted. It is almost working as I want, except for one instance of regex.test(). My code is as follows:
const first_name = document.getElementById("fname"); //text field
const last_name = document.getElementById("sname"); //text field
const email = document.getElementById("email"); //email field
const pass = document.getElementById("password"); //password field
const conf_pass = document.getElementById("cpassword"); //password field
const school = document.getElementById("school"); //text field
const reg_str = /^[a-z-]+$/i;
const reg_school = /^[a-zs]+$/i;
const reg_email = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/;
const reg_pass = /^(?=.*d)(?=.*[a-z])(?=.*[A-Z])[A-Za-zd]{8,}$/;
let error = "";
function validate() {
if(!reg_str.test(first_name.value)) {
error = "Please ensure that your first name only includes letters and hyphens.";
} else if(!reg_str.test(last_name.value)) {
error = "Please ensure that your last name only includes letters and hyphens.";
} else if(!reg_email.test(email.value)) {
error = "Check your email is of valid format.";
} else if(pass.value.length < 8) {
error = "Please choose a password that is at least 8 characters long.";
} else if(!reg_pass.test(pass.value)) {
error = "Please ensure password contains at least one uppercase, one lowercase and one digit.";
} else if(pass.value != conf_pass.value) {
error = "Passwords do not match, please check and try again.";
} else if(!reg_school.test(school.value)) {
error = "Please ensure that your school name only includes letters and spaces.";
}
if(error != "") {
alert(error);
return false;
} else {
return true;
}
}
Everything is working as expected except for the !reg_school.test(school.value)
conditional. It will pass successfully on the first form submission as required, but if it fails once then it will continue to fail indefinitely. Originally it was using the reg_str
regex, resulting in the same error (although only for the school, the names are working fine). I have seen similar queries around, but they always come back to the global tag in regex, which I have not used. What can I do to fix this?