My JavaScript function is not working properly when I try to submit a form on my website.
<form onsubmit="validateRegistration()">
<p>
// Email registration
<input type="text" id="e-mail" placeholder="Email" />
</p><p>
// Password registration
<input type="text" id="pswd" placeholder="Password" />
</p>
<br>
<input type="submit" class="submit">
</form>
I have made multiple attempts to link the JavaScript code with the HTML form, but whenever I click the submit button, none of the error alerts are displayed as expected.
// HTML
<form onsubmit="validateRegistration()">
<p>
<input type="text" id="e-mail" placeholder="Email" />
</p><p>
<input type="text" id="pswd" placeholder="Password" />
</p>
<br>
<input type="submit" class="submit">
</form>
// JavaScript
// Main Function
function validateRegistration(){
var email = document.getElementById('e-mail').value;
var password = document.getElementById('pswd').value;
var emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var emailResult = emailRegex.test(email);
if(emailResult == false){
alert("Please enter a valid email address");
return false;
}
var lowerCaseLetters = /[a-z]/g;
if(!password.match(lowerCaseLetters)) {
alert("Password must contain at least one lowercase letter!");
return false;
}
var upperCaseLetters = /[A-Z]/g;
if(!password.match(upperCaseLetters)){
alert("Password must contain at least one uppercase letter!");
return false;
}
var numbers = /[0-9]/g;
if(!password.match(numbers)){
alert("Password must contain at least one number!");
return false;
}
var specialCharacters = /[!@#$%^&*(),.?":{}|<>]/g;
if(!password.match(specialCharacters)){
alert("Password must contain at least one special character!");
return false;
}
if(password.length < 8){
alert("Password must be at least 8 characters long");
return false;
}
}
I am expecting the JavaScript code to display error messages when an invalid password is submitted and to show a "Thank you" message when both a valid email and password are submitted correctly.