Wed Sep 20 2023

Input Field Validation

JavaScript113 views
Input Field Validation

File Name: input-field-validation.js

// Validate Email Address
const validEmailFormat = (email) => {
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailPattern.test(email);
};

// Validate Input Fields
const fieldValid = (event, parentId) => {
  let field = event.target;
  let parentDiv = document.getElementById(parentId);

  if (!field.value) {
    parentDiv.classList.add("invalid");
    parentDiv.classList.remove("valid");
    return false;
  } else {
    if (field.name == "usrEmail") {
      if (!validEmailFormat(field.value.trim())) {
        parentDiv.classList.add("invalid");
        parentDiv.classList.remove("valid");
        return false;
      } else {
        parentDiv.classList.remove("invalid");
        parentDiv.classList.add("valid");
        return true;
      }
    } else {
      parentDiv.classList.remove("invalid");
      parentDiv.classList.add("valid");
      return true;
    }
  }
};

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.