Form Validation using Node.js

Posted by

Node.js Form Validation

.error {
color: red;
}

Node.js Form Validation

const form = document.getElementById(“myForm”);

form.addEventListener(“submit”, function(event) {
event.preventDefault();
let name = document.getElementById(“name”).value;
let email = document.getElementById(“email”).value;
let password = document.getElementById(“password”).value;
let nameError = document.getElementById(“nameError”);
let emailError = document.getElementById(“emailError”);
let passwordError = document.getElementById(“passwordError”);
let isValid = true;

if (name === “”) {
nameError.textContent = “Name is required”;
isValid = false;
} else {
nameError.textContent = “”;
}

if (email === “”) {
emailError.textContent = “Email is required”;
isValid = false;
} else if (!/S+@S+.S+/.test(email)) {
emailError.textContent = “Invalid email format”;
isValid = false;
} else {
emailError.textContent = “”;
}

if (password === “”) {
passwordError.textContent = “Password is required”;
isValid = false;
} else if (password.length < 6) {
passwordError.textContent = "Password must be at least 6 characters";
isValid = false;
} else {
passwordError.textContent = "";
}

if (isValid) {
form.submit();
}
});