Question

Using a form and javascript to validate fields.
Here is the code where I call the validation javascripts, all of which are in seperate documents but file path is specified.

    function validation()
    {
        return validateTitle()
            && validatefirstName()
            && validatesecondName()
            && validateAge()
            && validateEmail()
    }
    </script>
</head>
<body>
    <form name="subscribeForm" action="welcome.php" method="post" onsubmit="return validation();">

The last two, validateAge and validateEmail does not execute.
Here is the code for each javascript function:

function validateEmail()
{
    var x=document.getElementById('emailadd').value;
    var atpos=x.indexOf("@");
    var dotpos=x.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length || x == null)
    {
        alert("Not a valid e-mail address");
        return false;
    }
}

function validateAge()
{
    var b=document.forms["subscribeForm"]["bday"].value;
    if (b==null || b=="" || b < 1 || b > 105)
    {
        alert("Age invalid.");
        return false;
    }
    else if (isNaN(b))
    {
        alert("Please enter a numeric value.");
        return false;
    }
}
Was it helpful?

Solution

All your functions needs to return a thruty value if the validation passes. However, as soon as one function returns false or a falsey value, the validation process will halt. This is because the && operator uses short-circuit evaluation.

Basically, if validateTitle() fails, the rest of the functions won't get executed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top