-2

I'm trying to validate a HTML form using JavaScript, and I've tested all the validation functions seperately and when I do that they work fine, but when returning them all together for some reason only my validatename and validateEmail functions work, and I was wondering if anyone could give me tips on what I need to do to make it work? Here is the code I have:

<script type="text/javascript">

function validatename() 
        {
        var x = document.forms["feedback"]["fullname"].value;

        if (x == "") {
            alert('Name is not filled out');
            return false;
        }
} // validatename()   

</script>

<script type="text/javascript">

function validateEmail()
{
    var validemail = document.forms["feedback"]["email"].value;
    if (/(.+)@(.+)\.(.+)/.test(validemail)){
    return true;
    }
    else {
    alert('Invalid email or email not filled out')
    return false;
    }
} // validateEmail

    </script>

<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script>
function agecheck() {
    if($('input[name=age]:checked').length<=0)
    {
    alert("Please select your age");
    return false;
    }
} // agecheck

</script>

And then I return them in my HTML body through this:

<form name = feedback onsubmit=" validateEmail() && validatename() && agecheck() ">

EDIT: When I run the functions by exchanging the && for ; so I don't get a short circuit evaluation all of the functions do run, but for some reason if both validatename and validateEmail return as not false then agecheck won't run and thus won't throw up its alert when it should.

EDIT2: Ok so for some reason it was because of the fact that validatename either returned as false or undefined that the validateage wouldn't return, and I just fixed it to return as true or false rather than undefined or false which somehow fixed it. Thanks all for your help

TobyT
  • 1
  • 1
  • 1
    Note that your `validatename()` returns `undefined` or `false`, but it should return `true` or `false` if you want to use it with `&&`. The `&&` operator does a short-circuit evaluation, so unless `validateEmail()` and `validatename()` both return truthy values `agecheck()` won't be called. – nnnnnn Oct 18 '17 at 01:44
  • What do you mean when you say a function “works”? Does the last one not show an `alert`? Does it throw an error? Are you familiar with [short-circuit evaluation](https://stackoverflow.com/q/12554578/4642212)? – Sebastian Simon Oct 18 '17 at 01:45
  • Plus if you want this to prevent the form from submitting, then you must return a value _from_ the onsubmit attribute - `onsubmit="return (something that evaluates to true or false)"` – CBroe Oct 18 '17 at 01:46
  • @nnnnnn I didn't realise it should be true or fase to work with &&, but the short circuit evaluation is something I want because I would like it to throw out only one alert at a time when returning false so that if all 3 functions return fase it will only send out the first alert rather than going through and sending 3 alerts in a row – TobyT Oct 18 '17 at 01:55
  • @Xufox I just mean that it doesn't run. If I test one function at a time using onsubmit they all return how I would expect them to when evaluating as true or false, but if I try to return all functions at once then for some reason the validateage function doesn't return and thus won't throw up an alert and return false when I want it to. Is this likely because of the short circuit evaluation? – TobyT Oct 18 '17 at 01:59

3 Answers3

1

The example below is not intended to be a working solution. (meaning I did not test anything)

But that is an example of how I would write it... Only one function is needed.

<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script>

function validateForm(){

  //validate the name
  var x = document.forms["feedback"]["fullname"].value;
  if (x == "") {
    alert('Name is not filled out');
    return; // script ends right here if the name field is empty.
  }

  // validate the email
  var validemail = document.forms["feedback"]["email"].value;
  if (!/(.+)@(.+)\.(.+)/.test(validemail)){
    alert('Invalid email or email not filled out');
    return;  // script ends right here if the email field is incorrect.
  }

  // Validate the age
  if($('input[name=age]:checked').length<=0){
    alert("Please select your age");
    return;   // script ends right here if no age checkbox/radio field is checked.
  }

  // If the script wasn't halted already...
  alert("All fine! Let's submit.");

  //...
}
</script>

You may now call one function as an inline onsubmit if you like. I would do it another way... But there is many ways to validate a form. Now from the code you posted, that is all I can tell.

To really stop the submit to occur if there is a failed condition, you should read about preventDefault().

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
0

Try

<form name ="feedback" onsubmit="validateEmail();validatename();agecheck();">

OR

<form name ="feedback" onsubmit="function() { validateEmail(); validatename(); agecheck(); }">
Ramy M. Mousa
  • 5,727
  • 3
  • 34
  • 45
0

For some reason the fact that validatename returned as undefine or false rather than true or false was stopping the validateage from running successfully in all cases. Upon changing my code so that validatename returns as either true or false the validateage function is now working as intended.

TobyT
  • 1
  • 1
  • 1
    "For some reason"? That would be because that's how the `&&` operator is supposed to work: if its left-hand operand is falsy - and `undefined` is falsy - then it returns that value and doesn't even evaluate the right-hand operand so doesn't call your next function. Once you changed your functions to return `true` instead of `undefined` that meant the right-hand operand was evaluated, so the next function was called. – nnnnnn Oct 18 '17 at 06:22