javascript validating in the wrong order

function validateForm() {
    var name = document.forms["myForm"]["name"].value;
    if (name == undefined || name == null || name == "") {
        alert("Name must be filled out");
        return false;
    }

    var letters = /^[A-Za-z]+$/;
    if (name.match(letters)) {
        return true;
    } else {
        alert('Name must have alphabet characters only');
        document.forms["myForm"]["name"].focus();
        return false;
    }
}

function validateForm() {
    var unit = document.forms["myForm"]["unit"].value;
    if (unit == undefined || unit == null || unit == "") {
        alert("Unit must be filled out");
        return false;
    }

    var alpha = /^[0-9a-zA-Z]+$/;
    if (unit.match(alpha)) {
        return true;
    } else {
        alert('User address must have alphanumeric characters only');
        document.forms["myForm"]["unit"].focus();
        return false;
    }
}

The validation works but it starts from the unit field instead of the name, when I fill out the unit field with the right characters and submit it doesn't go back to validate the Name field, please need serious advice?

Upvotes: 0

Views: 41

Answers (1)

Pete
Pete

Reputation: 58442

You cannot have 2 functions with the same name as the second one will override the first. Merge the functions like so:

function validateForm() {
    var formIsValid = true;
  
    var name = document.forms["myForm"]["name"].value;
    if (name == undefined || name == null || name == "") {
        alert("Name must be filled out");
        formIsValid = false;
    } else  if (!name.match(/^[A-Za-z]+$/)) {
        alert('Name must have alphabet characters only');
        document.forms["myForm"]["name"].focus();
        formIsValid = false;
    }
  
    var unit = document.forms["myForm"]["unit"].value;
    if (unit == undefined || unit == null || unit == "") {
        alert("Unit must be filled out");
        formIsValid = false;
    } else if (!unit.match(/^[0-9a-zA-Z]+$/)) {
        alert('User address must have alphanumeric characters only');
        document.forms["myForm"]["unit"].focus();
        formIsValid = false;
    }
  
    return formIsValid;
}

Upvotes: 1

Related Questions