Signup Form Validation Using Vanilla JavaScript.
We will validate a signup form with pure JavaScript in which the user can't type the wrong details.
Follow the given steps.
- First, apply the given IDs to your input tag in the HTML corresponding to your form. And also in the form tag.
<!-- Add ID -->
<form id="signup">
<!-- For Name, User Name, and Full Name etc... -->
<input type="text" id="username" autocomplete="off" required>
<!-- For Email -->
<input type="email" id="email" autocomplete="off" required>
<!-- For Password -->
<input type="password" id="password" autocomplete="off" required>
<!-- For Confirm Password -->
<input type="password" id="confirm-password" autocomplete="off" required>
- Second, Add a small element after each input field. But don't type anything here because we're getting the text from JavaScript.
<small></small>
- Now, add these two classes in CSS. Here we're changing the border color if you want something else so you could give your custom styling to these classes.
.error input {
border-color: red;
}
.success input {
border-color: green;
}
- And then, add the given script to your JS file or between script tags.
// Getting Selectors
const usernameEl = document.querySelector("#username");
const emailEl = document.querySelector("#email");
const passwordEl = document.querySelector("#password");
const confirmPasswordEl = document.querySelector("#confirm-password");
const form = document.querySelector("#signup");
const checkUsername = () => {
let valid = false;
const min = 3,
max = 25;
const username = usernameEl.value.trim();
if (!isRequired(username)) {
showError(usernameEl, "Username cannot be blank.");
} else if (!isBetween(username.length, min, max)) {
showError(
usernameEl,
`Username must be between ${min} and ${max} characters.`
);
} else {
showSuccess(usernameEl);
valid = true;
}
return valid;
};
// Email Validation
const checkEmail = () => {
let valid = false;
const email = emailEl.value.trim();
if (!isRequired(email)) {
showError(emailEl, "Email cannot be blank.");
} else if (!isEmailValid(email)) {
showError(emailEl, "Email is not valid.");
} else {
showSuccess(emailEl);
valid = true;
}
return valid;
};
// Password Validation
const checkPassword = () => {
let valid = false;
const password = passwordEl.value.trim();
if (!isRequired(password)) {
showError(passwordEl, "Password cannot be blank.");
} else if (!isPasswordSecure(password)) {
showError(
passwordEl,
"Password must has at least 8 characters that include at least 1 lowercase character, 1 uppercase characters, 1 number, and 1 special character in (!@#$%^&*)"
);
} else {
showSuccess(passwordEl);
valid = true;
}
return valid;
};
// Confirm Password Validation
const checkConfirmPassword = () => {
let valid = false;
const confirmPassword = confirmPasswordEl.value.trim();
const password = passwordEl.value.trim();
if (!isRequired(confirmPassword)) {
showError(confirmPasswordEl, "Please enter the password again");
} else if (password !== confirmPassword) {
showError(confirmPasswordEl, "The password does not match");
} else {
showSuccess(confirmPasswordEl);
valid = true;
}
return valid;
};
// Regex for valid Email
const isEmailValid = (email) => {
const re =
/^(([^<>()\[\]\\.,;:\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,}))$/;
return re.test(email);
};
// Regex for secure Password
const isPasswordSecure = (password) => {
const re = new RegExp(
"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})"
);
return re.test(password);
};
const isRequired = (value) => (value === "" ? false : true);
const isBetween = (length, min, max) =>
length < min || length > max ? false : true;
const showError = (input, message) => {
const formField = input.parentElement;
// adding the error class and removing success
formField.classList.remove("success");
formField.classList.add("error");
// showing the error message
const error = formField.querySelector("small");
error.textContent = message;
};
const showSuccess = (input) => {
const formField = input.parentElement;
// removing the error class and Adding success
formField.classList.remove("error");
formField.classList.add("success");
// hiding the error message
const error = formField.querySelector("small");
error.textContent = "";
};
form.addEventListener("submit", function (e) {
// prevent the form from submitting
e.preventDefault();
// validate fields
let isUsernameValid = checkUsername(),
isEmailValid = checkEmail(),
isPasswordValid = checkPassword(),
isConfirmPasswordValid = checkConfirmPassword();
let isFormValid =
isUsernameValid &&
isEmailValid &&
isPasswordValid &&
isConfirmPasswordValid;
// submit to the server if the form is valid
if (isFormValid) {
}
});
const debounce = (fn, delay = 500) => {
let timeoutId;
return (...args) => {
// canceling the previous timer
if (timeoutId) {
clearTimeout(timeoutId);
}
// setting a new timer
timeoutId = setTimeout(() => {
fn.apply(null, args);
}, delay);
};
};
form.addEventListener(
"input",
debounce(function (e) {
switch (e.target.id) {
case "username":
checkUsername();
break;
case "email":
checkEmail();
break;
case "password":
checkPassword();
break;
case "confirm-password":
checkConfirmPassword();
break;
}
})
);
- All set :)
0 Comments