I have a registration form and I want to validate that the password and email fields by adding confirm fields for each. Both field must be validated before clicking on the submit button. Is there a way to validate both email and password fields on the same form. Below is what i have for my password fields which works great but i need help to validate the email section too on the same form. thanks in advance
<Form>
<input type="email" name="email" id="email" placeholder="Email" required />
<input type="email" name="confirm_email" id="confirm_email" placeholder="Confirm Email" required />
<input type="text" name="username" id="username" placeholder="Company name" required />
<input name="password" id="password" type="password" placeholder="Password" onkeyup='check();' />
<input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm Password" onkeyup='check();' />
<span id='message'></span>
</Form>
<script>
var check = function() {
if (document.getElementById('password').value ==
document.getElementById('confirm_password').value) {
document.getElementById('message').style.color = 'green';
document.getElementById('message').innerHTML = 'Password match confirmed';
} else {
document.getElementById('message').style.color = 'red';
document.getElementById('message').innerHTML = 'Please confirm your password.';
}
}</script>
You need to check for the attributes using getAttribute() on where which input is being typed in and then from their you can do the validation of your email first.
Also, to make sure that email is always getting confirmed first we need to set a global variable which is initially false but as soon the email is confirmed it becomes true and then you can move on to the password feilds.
If you directly goes towards the password the input you will see the message that please verify you email first.
Lastly, i have cleaned up your and is simplified the code as well by declaring the inputs as variable so that we can use them again in our code if needed. I have also added when input field must not be empty when doing the validation of fields.
Live Working Demo:
var emailConfirmed = false
var message = document.getElementById('message')
var email = document.getElementById('email')
var confEmail = document.getElementById('confirm_email')
var password = document.getElementById('password')
var confPassword = document.getElementById('confirm_password')
function check(e) {
if (e.getAttribute('id') == 'email' || e.getAttribute('id') == 'confirm_email') {
if (email.value != '' && confEmail.value != '' && email.value == confEmail.value) {
message.style.color = 'green';
message.innerHTML = 'Email match confirmed';
emailConfirmed = true
} else {
message.style.color = 'red';
message.innerHTML = 'Please confirm your email.';
emailConfirmed = false
}
}
if (e.getAttribute('id') == 'password' || e.getAttribute('id') == 'confirm_password') {
if (emailConfirmed) {
if (password.value != '' && confPassword.value != '' && password.value == confPassword.value) {
message.style.color = 'green';
message.innerHTML = 'Password match confirmed';
} else {
message.style.color = 'red';
message.innerHTML = 'Please confirm your password.';
}
} else {
message.style.color = 'red';
message.innerHTML = 'Please confirm your email first.'
}
}
}
input {
display: block;
}
<form>
<input type="email" name="email" id="email" placeholder="Email" onkeyup='check(this);' required />
<input type="email" name="confirm_email" id="confirm_email" placeholder="Confirm Email" onkeyup='check(this);' required />
<input name="password" id="password" type="password" placeholder="Password" onkeyup='check(this);' />
<input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm Password" onkeyup='check(this);' />
<br>
<span id='message'></span>
</form>
Related
I have a task:
Write a JS function that validates the content of the form - the form should have at least one mandatory numeric field and one field that simply cannot be empty. If the validation is not passed through the field, display the appropriate information to inform the user. If validation fails, the function should return false, otherwise true
So, I'm trying to return a boolean value if the from fails validation and subsequently hide the forms. I've put the boolean value into the error and success functions but it doesn't seem to work. I've tried to make the check inputs function return the boolean value but it didn't work also.
I'm just trying to learn so any help regarding the best approach to this problem logically would be appreciated. I also understand that there might have been simple syntax issues, but this is also something I'm trying to get better at right now.
const form = document.getElementById('form');
const username = document.getElementById('username');
const num = document.getElementById('num');
const phone = document.getElementById('phone');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
let isValid;
form.addEventListener('submit', e => {
e.preventDefault();
checkInputs();
if (isValid = true){
form.remove;
}
});
function checkInputs() {
const usernameValue = username.value.trim();
const numValue = num.value.trim();
const phoneValue = phone.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
const password2Value = password2.value.trim();
if(usernameValue === '') {
setErrorFor(username, 'Username cannot be blank');
} else {
setSuccessFor(username);
}
if(numValue === ''){
setErrorFor(num, 'You must have a favorite number');
}else if(isNaN(numValue)){
setErrorFor(num, 'Not a number');
}else{
setSuccessFor(num);
}
if(phoneValue === '+48' || phoneValue === ''){
setErrorFor(phone, 'Phone cannot be blank');
}else{
setSuccessFor(phone);
}
if(emailValue === '') {
setErrorFor(email, 'Email cannot be blank');
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Not a valid email');
} else {
setSuccessFor(email);
}
if(passwordValue === '') {
setErrorFor(password, 'Password cannot be blank');
}else if (passwordValue.length < 8){
setErrorFor(password, 'Password cannot be less than 8 characters');
} else {
setSuccessFor(password);
}
if(password2Value === '') {
setErrorFor(password2, 'Password cannot be blank');
} else if(passwordValue !== password2Value) {
setErrorFor(password2, 'Passwords does not match');
} else{
setSuccessFor(password2);
}
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
formControl.className = 'form-control error';
small.innerText = message;
isValid = false;
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
isValid = true;
}
function isEmail(email) {
return /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}
function test(){
if (isValid = true){
console.log('hi')
} else{
console.log('HEXYU')
}
}
<div class="container">
<div class="header">
<h2>Create Account</h2>
</div>
<form id="form" class="form">
<div class="form-control">
<label for="username">Username</label>
<input type="text" placeholder="Your username" id="username" />
<small>Error message</small>
</div>
<div class="form-control">
<label for="num">Your favorite number</label>
<input type="number" placeholder="Your favorite number" id="num"/>
<small>Error message</small>
</div>
<div class="form-control">
<label for="phone">Phone number</label>
<input type="tel" placeholder="Your phone numbe" id="phone" value="+48"/>
<small>Error message</small>
</div>
<div class="form-control">
<label for="email">Email</label>
<input type="email" placeholder="email#youremail.com" id="email" />
<small>Error message</small>
</div>
<div class="form-control">
<label for="password">Password</label>
<input type="password" placeholder="Password" id="password"/>
<small>Error message</small>
</div>
<div class="form-control">
<label for="passsword2">Password check</label>
<input type="password" placeholder="Repeat your password" id="password2"/>
<small>Error message</small>
</div>
<button class="form-button" >Submit</button>
</form>
</div>
Two errors in your code:
Use remove() instead of remove
Use == / === instead of =
Also, you could use required to let user unable to submit.
num input type will only accept number input and email type input will check if there is # in the input. This will save a lot of if unnecessary if statement.
const form = document.getElementById('form');
const username = document.getElementById('username');
const num = document.getElementById('num');
const phone = document.getElementById('phone');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
let isValid;
form.addEventListener('submit', e => {
e.preventDefault();
checkInputs();
if (isValid = true){
form.remove();
}
});
function checkInputs() {
const phoneValue = phone.value.trim();
const passwordValue = password.value.trim();
const password2Value = password2.value.trim();
setSuccessFor(username);
setSuccessFor(num);
setSuccessFor(email);
}
if(phoneValue === '+48' ){
setErrorFor(phone, 'Phone cannot be blank');
}else{
setSuccessFor(phone);
}
if (passwordValue.length < 8){
setErrorFor(password, 'Password cannot be less than 8 characters');
} else {
setSuccessFor(password);
}
if(passwordValue !== password2Value) {
setErrorFor(password2, 'Passwords does not match');
} else{
setSuccessFor(password2);
}
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
formControl.className = 'form-control error';
small.innerText = message;
isValid = false;
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
isValid = true;
}
function isEmail(email) {
return /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}
function test(){
if (isValid == true){
console.log('hi')
} else{
console.log('HEXYU')
}
}
<form id="form" class="form">
<div class="form-control">
<label for="username">Username</label>
<input type="text" placeholder="Your username" id="username" />
<small>Error message</small>
</div>
<div class="form-control">
<label for="num">Your favorite number</label>
<input type="number" placeholder="Your favorite number" id="num" required />
<small>Error message</small>
</div>
<div class="form-control">
<label for="phone">Phone number</label>
<input type="tel" required placeholder="Your phone numbe" id="phone" value="+48"/>
<small>Error message</small>
</div>
<div class="form-control">
<label for="email">Email</label>
<input type="email" required placeholder="email#youremail.com" id="email" />
<small>Error message</small>
</div>
<div class="form-control">
<label for="password">Password</label>
<input type="password" required placeholder="Password" id="password"/>
<small>Error message</small>
</div>
<div class="form-control">
<label for="passsword2">Password check</label>
<input type="password" required typeplaceholder="Repeat your password" id="password2"/>
<small>Error message</small>
</div>
<button class="form-button" >Submit</button>
</form>
</div>
This is a two-part question.
Part 1. The passConfirm function that I currently have is there to make sure that the password and confirming password values match. Right now, when I type in my password the button disappears. The purpose of this function is to display a message while the user is creating a password and confirming it, that the password does or does not match. Does anyone know why that is happening based on the code I have?
Part 2. Is there a way to refactor my passConfirm function? I tried doing it by adding it to the validateForm function (Please see commented code for my example). It wasn't working tho.
function printError(elemId, message) {
document.getElementById(elemId).innerHTML = message;
}
function validateForm() {
event.preventDefault();
var name = document.regForm.FullName.value;
var email = document.regForm.email.value;
var phone = document.regForm.phone.value;
var password = document.regForm.Password.value;
var confirmPassword = document.regForm.ConfirmPassword.value;
const phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
var nameError = emailError = phoneError = passwordError = true;
//Empty name input error message
if (name == "") {
printError("nameError", "Please enter your name")
}
//Empty email input error message
if (email == "") {
printError("emailError", "Please enter a valid email")
}
//Empty phone input error message
if (phone == "") {
printError("phoneError", "Please enter your phone numnber")
}
//Non valid phone number error messsage
if (phone.match(phoneno)) {
return true;
} else {
printError("phoneError", "Please enter a valid phone number")
}
//Empty Password input
if (password == "") {
printError("passwordError", "Please enter a password")
}
//Empty Cofirm Password input
if (confirmPassword == "") {
printError("confirmpassError", "Please confirm your password")
}
//I tried refactoring the passConfirm function and additing it here.
//if (password.match(confirmPassword)) {
// printPass("matchingPassword", "Passwords match")
// document.getElementById("matchingPassword").style.color = "green";
//} else {
// printPass("matchingPassword", "Passwords do no match")
// document.getElementById("matchingPassword").style.color = "red";
//}
};
var passConfirm = function() {
if (document.getElementById("Password").value == document.getElementById("ConfirmPassword").value) {
document.getElementById("matchingPassword").style.color = "green";
document.getElementById("matchingPassword").style.fontWeight = "Heavy";
document.getElementById("matchingPassword").innerHTML = "Passwords match!"
} else {
document.getElementById("matchingPassword").style.color = "red";
document.getElementById("matchingPassword").style.fontWeight = "Heavy";
document.getElementById("matchingPassword").innerHTML = "Passwords do NOT match!"
}
}
fieldset {
width: 420px;
height: 950px;
}
<h1>Hello, please register!</h1>
<div class="container">
<form name="regForm" class="form" onsubmit="return validateForm(event)">
<fieldset>
<div class="row">
<label>Full Name</label></br>
<input name="FullName" type="text" placeholder="John Doe" id="FullName" />
<span class="error" id="nameError"></span>
</div>
<div class="row">
<label>Email</label></br>
<input name="email" type="email" placeholder="johndoe#email.com" id="Email" />
<span class="error" id="emailError"></span>
</div>
<div class="row">
<label>Phone Number</label></br>
<input name="phone" type="tel" placeholder="(123) 456-7890" id="PhoneNumber" />
<span class="error" id="phoneError"></span>
</div>
<div class="row">
<label>Password</label></br>
<input name="Password" id="Password" type="Password" placeholder="Password" onchange='passConfirm();' />
<span class="error" id="passwordError"></span>
</div>
<div class="row">
<label>Confirm Password</label></br>
<input name="ConfirmPassword" id="ConfirmPassword" type="Password" placeholder="Confirm Password" onchange='passConfirm();' />
<span class="error" id="confirmpassError"></span>
</div>
<span id="matchingPassword">
<button type="submit" value="submit">Sign Me Up!</button>
</fieldset>
</form>
</div>
Your button disappears because you use InnerHTML method to display the message, which overrides it. Though your logic works after passwords match when you press enter, you lose your button element. It is better to use a separate div or paragraph tag to display your message and keep your button as it is since it's part of the form.
Here is the change you can try
<span id="matchingPassword">
<button type="submit" value="submit">Sign Me Up!</button></span>
<p id="message"></p>
</fieldset>
var passConfirm = function() {
if (document.getElementById("Password").value == document.getElementById("ConfirmPassword").value) {
document.getElementById("message").style.color = "green";
document.getElementById("message").style.fontWeight = "Heavy";
document.getElementById("message").innerHTML = "Passwords match!"
} else {
document.getElementById("message").style.color = "red";
document.getElementById("message").style.fontWeight = "Heavy";
document.getElementById("message").innerHTML = "Passwords match!"
}
}
I have a problem. When I clicked the submit button nothing happens, even when I filled out the username and password with numbers (I don't want the username and password contains any number so I did make the condition for it), there is no alert display. I do not know where the problem comes from? Can you guys help me with this
Note: the reset function works fine
function validateInput() {
var firstName = document.forms["sign_up"]["firstName"];
var lastName = document.forms["sign_up"]["lastName"];
var email = document.forms["sign_up"]["email"];
var reg = /^[a-zA-Z]+$/;
if (firstName.value !== '' || lastName.value !== '' || email.value !== '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
// return true;
return false; // for the demo, so it doesn't submit
} else {
if (firstName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in username";
return false;
} else if (lastName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in password";
return false;
}
}
}
}
function reset() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("email").innerHTML = "";
}
<form id="sign_up" onsubmit="return validateInput()">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">Submit</button>
<button type="button" onclick="reset();">Cancel</button>
</form>
Use the Pattern attribute in input for validation like below
<input type="text" id="firstName" value="" pattern="[^0-9]*" title="Numbers are not allowed" placeholder="Enter your first name">
for more references: https://www.w3schools.com/tags/att_input_pattern.asp
And for reset functionality use reset
<input type="reset" value="reset">
It's better than create a special function for it and it saves your number of lines:-)
First, try to avoid to inline event handlers as they are not rec-emended at all. Also to reset form values you can simply use reset() method on the form.
Also, do not use innerHTML just to set the text of your error. You can use textContent instead which is better fit in your example.
You can use addEventListener with submit event to check for validation on your firstname and lastname.
I have fixed your code and its all working as expected.
Live Working Demo:
let form = document.getElementById("sign_up")
var firstName = document.getElementById("firstName")
var lastName = document.getElementById("lastName")
var email = document.getElementById("email")
var reset = document.getElementById("clearValues")
var reg = /^[a-zA-Z]+$/;
form.addEventListener('submit', function(e) {
e.preventDefault()
if (firstName.value != '' || lastName.value != '' || email.value != '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
} else if (!firstName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in username";
} else if (!lastName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in password";
}
}
})
reset.addEventListener('click', function(e) {
document.getElementById("sign_up").reset();
})
input {
display:block;
}
<head>
</head>
<body>
<form id="sign_up" action="#">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">
Submit
</button>
<button type="button" id="clearValues" onclick="reset();">
Cancel
</button>
</form>
</body>
You don't need to return a function in onsubmit event. This should work fine.
<form id="sign_up" onsubmit="validateInput()">
Reference:
https://www.w3schools.com/jsref/event_onsubmit.asp
So I'm trying to check if the user inputs the same email address and password twice in a signup form using javascript. It shouldn't let them sign up if they don't match, however only the portion of the passwords is working and the email isn't working. Here's my code:
<form>
<input type="email" name="fname" placeholder="Email Adress" required="required" class="input-txt" id="email1">
<input type="email" name="fname" placeholder="Confirm Email Adress" required="required" class="input-txt" id="email2">
<br><br>
<input id="password" type="password" name="fname" placeholder="Create Password" required="required" class="input-txt">
<input id="confirm_password" type="password" name="fname" placeholder="Confirm Password" required="required" class="input-txt"><br>
<button type="submit" class="btn">Sign up</button>
</form>
<script>
function validateMail() {
if(first_email.value != second_email.value) {
email2.setCustomValidity("Emails Don't Match");
} else {
email2.setCustomValidity('');
}
}
email1.onchange = validateMail;
email2.onkeyup = validateMail;
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
</script>
You need to assign var in top of the script:
var first_email = document.getElementById("email1")
, second_email = document.getElementById("email2")
, password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
I am trying to do client-side validation using javascript and all the things are working properly, only it doesn't redirect to another page -> redirect.html
After clicking on the alert pop-up it again loads the index.html.
document.getElementById('sub-btn').addEventListener('click', function() {
var firstName = document.getElementById('fname').value;
var lastName = document.getElementById('lname').value;
var yearBirth = document.getElementById('dob').value;
var phoneNum = document.getElementById('ph-no').value;
var emailID = document.getElementById('email').value;
var password = document.getElementById('password').value;
var rePassword = document.getElementById('re-password').value;
if (firstName.length === 0) {
alert('Enter the first name!');
}else if (lastName.length === 0) {
alert('Enter the last name!');
}else if (yearBirth.length === 0) {
alert('Enter date of birth!');
}else if (phoneNum.length === 0) {
alert('Enter the phone number!');
}else if (phoneNum.length > 10) {
alert('Check phone number!');
}else if (emailID.length === 0) {
alert('Enter the email ID !');
}else if (password.length === 0 && (rePassword.length === 0 || rePassword.length !== 0)) {
alert('Enter the password!');
}else if (rePassword.length === 0) {
alert('Re-enter the password!');
}else {
alert('Redirecting to another page....');
window.location = 'redirect.html';
} });
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8"></meta>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Sign Up</title>
</head>
<body>
<div class="main">
<div class="form-box">
<form class="input">
<input class="input-field" id="fname" placeholder="First Name" type="text">
<input class="input-field" id="lname" placeholder="Last Name" type="text">
<input class="input-field" id="dob" placeholder="Date of Birth" type="date">
<input class="input-field" id="ph-no" placeholder="Phone Number" type="text">
<input class="input-field" id="email" placeholder="Email ID" type="email">
<input class="input-field" id="password" placeholder="Enter Password" type="password">
<input class="input-field" id="re-password" placeholder="Re-enter Password" type="password">
<button class="btn" id="sub-btn" type="submit">SIGN UP</button>
</form>
</div>
</div>
</body>
<script src="script.js" type="text/javascript"></script>
</html>
Referring the link button type submit/button
document.getElementById('sub-btn').addEventListener('click', function() {
var firstName = document.getElementById('fname').value;
var lastName = document.getElementById('lname').value;
var yearBirth = document.getElementById('dob').value;
var phoneNum = document.getElementById('ph-no').value;
var emailID = document.getElementById('email').value;
var password = document.getElementById('password').value;
var rePassword = document.getElementById('re-password').value;
if (firstName.length === 0) {
alert('Enter the first name!');
}else if (lastName.length === 0) {
alert('Enter the last name!');
}else if (yearBirth.length === 0) {
alert('Enter date of birth!');
}else if (phoneNum.length === 0) {
alert('Enter the phone number!');
}else if (phoneNum.length > 10) {
alert('Check phone number!');
}else if (emailID.length === 0) {
alert('Enter the email ID !');
}else if (password.length === 0 && (rePassword.length === 0 || rePassword.length !== 0)) {
alert('Enter the password!');
}else if (rePassword.length === 0) {
alert('Re-enter the password!');
}else {
alert('Redirecting to another page....');
window.location = 'redirect.html';
} });
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8"></meta>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Sign Up</title>
</head>
<body>
<div class="main">
<div class="form-box">
<form class="input">
<input class="input-field" id="fname" placeholder="First Name" type="text">
<input class="input-field" id="lname" placeholder="Last Name" type="text">
<input class="input-field" id="dob" placeholder="Date of Birth" type="date">
<input class="input-field" id="ph-no" placeholder="Phone Number" type="text">
<input class="input-field" id="email" placeholder="Email ID" type="email">
<input class="input-field" id="password" placeholder="Enter Password" type="password">
<input class="input-field" id="re-password" placeholder="Re-enter Password" type="password">
<button class="btn" id="sub-btn" type="button">SIGN UP</button>
</form>
</div>
</div>
</body>
<script src="script.js" type="text/javascript"></script>
</html>
you need to add event preventdefault I think
document.getElementById('sub-btn').addEventListener('click', function(e) {
e.preventDefault()
var firstName = document.getElementById('fname').value;
var lastName = document.getElementById('lname').value;
var yearBirth = document.getElementById('dob').value;
var phoneNum = document.getElementById('ph-no').value;
var emailID = document.getElementById('email').value;
var password = document.getElementById('password').value;
var rePassword = document.getElementById('re-password').value;
if (firstName.length === 0) {
alert('Enter the first name!');
}else if (lastName.length === 0) {
alert('Enter the last name!');
}else if (yearBirth.length === 0) {
alert('Enter date of birth!');
}else if (phoneNum.length === 0) {
alert('Enter the phone number!');
}else if (phoneNum.length > 10) {
alert('Check phone number!');
}else if (emailID.length === 0) {
alert('Enter the email ID !');
}else if (password.length === 0 && (rePassword.length === 0 || rePassword.length !== 0)) {
alert('Enter the password!');
}else if (rePassword.length === 0) {
alert('Re-enter the password!');
}else {
alert('Redirecting to another page....');
window.location = 'redirect.html';
} });
form already has a built in redirect functionality by using the attribute action which also provides the benefit of actually posting the data to the desired link, if required.
Furthermore form has an event onsubmit which gets executed before submitting the form and can be cancelled by returning false.
Since all the mentioned requirements for your code are already given by the default behaviour of form, there is less reason not to use it.
Here is what you would need to change:
Instead of defining a click event, you define a standalone validation
function (=myValidator()), which returns true once all criterias are fulfilled and
false until. This better good practise anyway, since you can call it
independent of click events.
Setting the actionof the form to the desired URL (=redirect.html)
Forward the return of myValidator() to the onsubmit event on the form
function myValidator(){
//REM: returns true once valid, false until.
var tReturn = true;
var firstName = document.getElementById('fname').value;
var lastName = document.getElementById('lname').value;
var yearBirth = document.getElementById('dob').value;
var phoneNum = document.getElementById('ph-no').value;
var emailID = document.getElementById('email').value;
var password = document.getElementById('password').value;
var rePassword = document.getElementById('re-password').value;
if (firstName.length === 0) {
alert('Enter the first name!');
tReturn = false
}else if (lastName.length === 0) {
alert('Enter the last name!');
tReturn = false
}else if (yearBirth.length === 0) {
alert('Enter date of birth!');
tReturn = false
}else if (phoneNum.length === 0) {
alert('Enter the phone number!');
tReturn = false
}else if (phoneNum.length > 10) {
alert('Check phone number!');
tReturn = false
}else if (emailID.length === 0) {
alert('Enter the email ID !');
tReturn = false
}else if (password.length === 0 && (rePassword.length === 0 || rePassword.length !== 0)) {
alert('Enter the password!');
tReturn = false
}else if (rePassword.length === 0) {
alert('Re-enter the password!');
tReturn = false
};
return tReturn
}
<!--REM: It is better practise to assign those events using javascript - I merely leave it here to point put the event/difference -->
<form class="input" action="redirect.html" onsubmit="return myValidator()">
<input class="input-field" id="fname" placeholder="First Name" type="text">
<input class="input-field" id="lname" placeholder="Last Name" type="text">
<input class="input-field" id="dob" placeholder="Date of Birth" type="date">
<input class="input-field" id="ph-no" placeholder="Phone Number" type="text">
<input class="input-field" id="email" placeholder="Email ID" type="email">
<input class="input-field" id="password" placeholder="Enter Password" type="password">
<input class="input-field" id="re-password" placeholder="Re-enter Password" type="password">
<button class="btn" id="sub-btn" type="submit">SIGN UP</button>
</form>
Also note that empty inputs can nowadays be prevented by using the attribute required as well as other nice form-features and be styled accordingly using pseudo-css-classes.
<form class="input" action="redirect.html">
<input class="input-field" id="fname" placeholder="First Name" type="text" required>
<input class="input-field" id="lname" placeholder="Last Name" type="text" required>
<input class="input-field" id="dob" placeholder="Date of Birth" type="date" required>
<input class="input-field" id="ph-no" placeholder="Phone Number" type="text" required>
<input class="input-field" id="email" placeholder="Email ID" type="email" required>
<input class="input-field" id="password" placeholder="Enter Password" type="password" required>
<input class="input-field" id="re-password" placeholder="Re-enter Password" type="password" required>
<button class="btn" id="sub-btn" type="submit">SIGN UP</button>
</form>