본문 바로가기

Mini Projects

Form Validator (2) - Add Simple Validation

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);
  }
});