Reputation: 21
I have a multistep form needs additional validation for password, email, credit card expiry date. As there is a function validateForm I want to add to this so that it also checks the password has 8 char and email is valid ('@').
The main issue is the for loop that says input is valid/invalid before allowing user to go to next step in form. At the moment it just checks if there is anything in each box, if so it goes next page. I need it to also check that the password/email is valid as per above requests.
var currentTab = 0;
showTab(currentTab);
function showTab(n) { /*need to add in password/email validation to below but unsure how */
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Complete Order";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
fixStepIndicator(n)
}
function nextPrev(n) {
var x = document.getElementsByClassName("tab");
if (n == 1 && !validateForm()) return false;
x[currentTab].style.display = "none";
currentTab = currentTab + n;
if (currentTab >= x.length) {
document.getElementById("orderForm").submit();
return false;
}
showTab(currentTab);
}
function validateForm() {
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
for (i = 0; i < y.length; i++) {
if (y[i].value == "") {
y[i].className += "invalid";
valid = false;
}
}
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid;
}
Upvotes: 2
Views: 391
Reputation: 46833
Assuming you can edit the HTML elements and add id's to the input fields, you can simply use document.getElementById
to get each specific input.
<html>
<body>
<input type="password" id="myPassword" />
<input type="email" id="myEmail" />
</body>
</html>
function validateForm() {
const pwInput = document.getElementById('myPassword');
if( pwInput && pwInput.value.length < 5) {
console.log('password not valid');
}
const emailInput = document.getElementById('myEmail');
if(emailInput && emailInput.search(/@/) === -1) {
console.log('email not valid');
}
}
This sounds like homework, so this is some additional food for thought for production code.
While doing password validation on the client side is okay, server side must absolutely do password validation.
Email validation is very tricky to do. You can use a regex you find, but even the ones on Stack Overflow are filled with caveats and test cases that don't work. For production code, using a library along with email verification is your best bet.
Upvotes: 1