get Elements
const form = document.getElementById("form");
const username = document.getElementById("username");
const email = document.getElementById("email");
const password = document.getElementById("password");
const password2 = document.getElementById("password2");
Add Event Listeners
//Event Listeners
form.addEventListener("submit", function (e) {
e.preventDefault();
if (username.value === "") {
showError(username, "Username is required.");
} else {
showSuccess(username);
}
}
make showError function
// Show input error message
function showError(input, message) {
const formControl = input.parentElement;
formControl.className = "form-Control error";
const small = formControl.querySelector("small");
small.innerText = message;
}
make showSuccess function
// Show Success Outline
function showSuccess(input) {
const formControl = input.parentElement;
formControl.className = "form-Control success";
}
add other elements to event listener
//Event Listeners
form.addEventListener("submit", function (e) {
e.preventDefault();
if (username.value === "") {
showError(username, "Username is required.");
} else {
showSuccess(username);
}
if (email.value === "") {
showError(email, "Email is required.");
}else{
showSuccess(email);
}
if (password.value === "") {
showError(password, "Password is required.");
} else {
showSuccess(password);
}
if (password2.value === "") {
showError(password2, "Password2 is required.");
} else {
showSuccess(password2);
}
});
add email validation function
// Check email is valid
function isValidEmail(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(String(email).toLowerCase());
}
add email validation function to eventListner
//Event Listeners
form.addEventListener("submit", function (e) {
e.preventDefault();
if (username.value === "") {
showError(username, "Username is required.");
} else {
showSuccess(username);
}
if (email.value === "") {
showError(email, "Email is required.");
}else if(!isValidEmail(email.value){
showError(email, 'Email is not valid.')
}else{
showSuccess(email);
}
if (password.value === "") {
showError(password, "Password is required.");
} else {
showSuccess(password);
}
if (password2.value === "") {
showError(password2, "Password2 is required.");
} else {
showSuccess(password2);
}
});
'Mini Projects' 카테고리의 다른 글
Form Validatior (4) - Check Length, Email & Password match (0) | 2020.07.09 |
---|---|
Form Validator (3) - Check Required & Refactor (0) | 2020.07.09 |
Form Validator (1) HTML & Base CSS (0) | 2020.07.09 |
Knowledge TimeLine (5) Scroll in Animation (0) | 2020.07.08 |
Knowledge Timeline (4) Responsive Media Query (0) | 2020.07.08 |