onsubmit multiple javascript functions
Asked Answered
E

7

10

Does anyone know how to onsubmit multiple functions? What I intented to do was: onsubmit checks if all these functions return true, if all of them return true, then I do the action="checked.html"

<form id="myForm" name="myForm" action="checked.html" method="post"
onsubmit="return validateName() || validatePhone() || validateAddress() ||
validateEmail()">

However, what actually happened was, the computer checks the code from left to right, and the result of the next function will replace the previous one, and so on, until the end. So, even if all the 3 first functions return false, as long as the last one is true, the computer will execute action="checked.html", which is not what I intented to do... can anyone please help me on this, it's been like 4 hours I'm trying to fix it :S Thanks!

Also, when I tried to do something like <form onsubmit="return verify1() && verify2()">, it doesn't work, all it does is to check verify1(), and not the following ones... :(

CLARIFCATION: On submit, I want four validation functions to be called. Submit should be prevented unless all four functions return true, but all four should always be called even if some of them return false.

Effectually answered 4/8, 2012 at 5:40 Comment(4)
You can directly write function instead of use OR and AND operator,Like onsubmit="return validateName();validatePhone();validateAddress();validateEmail();"Spruik
@Harry -1; how on earth could this work? as soon as validateName returns true the form will submitBesetting
@Harry: I don't think you can do that. It will just return the first function result.Concinnity
The boolean operators || and && have a short-circuiting mechanism. For ||, if the first operator is true, the whole expression must be true. So why check the second operator? For &&, if the first operator is false, the whole expression must be false.Cursive
I
22

Use & instead of &&.

&& uses short-circuit evaluation and so doesn't evaluate the right-hand operand if the left-hand operand is falsy.

& always evaluates both operands.

onsubmit="return !!(validateName() & validatePhone()
                      & validateAddress() & validateEmail());"

EDIT: Sorry, I forgot that & won't return an actual boolean. Wrap the expression in parentheses and use a double ! to convert it as (now) shown. (You wouldn't need to worry if using the result in an if test, but the return value from the event handler should be an actual boolean.)

P.S.: Here's a rather clunky demo to show that all four functions get called but produce the overall true or false result that you need: http://jsfiddle.net/nnnnnn/svM4h/1/

Idiom answered 4/8, 2012 at 6:20 Comment(6)
why do you need to evaluate both operands? I mean if at least one validation fails, isn't the form going to be invalid?Concinnity
@Concinnity actually nnnnnn might have a point here OP may have something in each validation function that highlights the input it checks as invalid. Perhaps its this that the OP wants to work...Besetting
@Concinnity - I guess he or she wants all validations to be run so the user is made aware of all problems at once - maybe the individual validation functions highlight errors by changing background colours or something. I'm simply telling him or her how to do it, not whether it is a good idea or not, though as a user I prefer to see all errors at once...Idiom
basically, in each function, it checks if the input users type in correspond to the rules, for example, for validatePhone(), it checks if the input are all numbers, if not, it gives an alert. And it's like this for each function..Effectually
The code I've shown will do that. But I'd recommend against displaying multiple alerts, it's annoying to the user. (I know I did it in my demo, but that was just a demo to show how & meets your requirements.) Better to display a single alert at the end with a summary of all errors. Or highlight the invalid fields with a different colour and display a message asking the user to correct those fields.Idiom
@nnnnnn: I saw the clarification update in the question and it does work if the op really wants this behaviour. +1Concinnity
B
8

Change your code to use AND instead of OR

onsubmit="return validateName() && validatePhone() && validateAddress() && validateEmail()"

The reason being that if you use OR once that first function returns true javascript won't bother to check the other functions. Also you don't want to use OR because if the first check was false and second is true the form will still submit since at least one of your checks is TRUE.

See fiddle to show this works, both checks execute and show an alert message but because check2 returns false the form doesn't submit - if you want play around with the return results of checks1 and check2 functions and the use of && and ||

After understanding the problem better, you need to use a single &, but because true & true returns 1 and not true you need to write it like this

onsubmit="return ((validateName() & validatePhone() & validateAddress() & validateEmail()) == 1)"

Besetting answered 4/8, 2012 at 5:44 Comment(6)
I tried this but it only checks validateName() and not the others.. :SEffectually
@user1561559 see added fiddle - this works! it implies that theres a problem with your validation functions...Besetting
Your fiddle works because the first function returns true. If you change it so the first function returns false then the second function doesn't get called. OP wants all the functions to be called regardless of what they return individually, but then to return the result of ANDing all their individual returns.Idiom
does anyone have any other idea how to do this :S None is the answers work :(Effectually
@Idiom i see the problem now the all validation functions must execute as well return true - and as suggestion a single & should be usedBesetting
All validation functions must execute, but only if all return true should the submit continue...Idiom
T
3

if all you need is make sure all functions return true before proceeding, then use && not || and to insure that the expression does not get evaluated pre-maturally by the return function put some extra brackets

<form id="myForm" name="myForm" action="checked.html" method="post"
onsubmit="return (validateName() && validatePhone() && validateAddress() &&
validateEmail() )">
Twenty answered 4/8, 2012 at 5:44 Comment(6)
yea I tried, but it only checks validateName() and not the others.. :SEffectually
did you try adding another set of brackets to ensure?Twenty
if ValidateNames() is false, then there is no need to validate the rest of the condition. Which is why && is used. Are you saying that even if the rest of the functions return false, but validateNames() is true then the overall return is TRUE?Twenty
nop, only the last one influence the overall, hence validateEmail(). If validateEmail() returns true, then overall is true, the rest don't matterEffectually
@user1561559 If you only need the last to be true, then make them separate statements and return only the last result -- onsubmit="validateName(); validatePhone(); validateAddress(); return validateEmail();"Zacynthus
no no, u misunderstood me :D I want to check if all are true, but my thingy only use the last one to influence the overall result, hence if last is false, then overall is false :( and your script only checks if the first one is true or false, and dont care about the others :S Any more idea? :((Effectually
M
3

Create a wrapper function, which call each function and checks their return value. At any time if the return value is false you can either stop the form submit by returning false at that time or evaluate the rest of the things and finally return false.

So JS a code that will do what you want is :

function validateForm() {
    var isFormValid = true;
    isFormValid &= validateName();
    isFormValid &= validatePhone();
    isFormValid &= validateAddress();
    isFormValid &= validateEmail();
    return isFormValid? true:false;
}

Now in the form simply use :

<form id="myForm" name="myForm" action="checked.html" method="post" onsubmit="return validateForm();">

Here is a working JSFiddle Example.

EDIT : Made a boo boo below, corrected.

Using OR was incorrect, but the reason AND is not working how you are expecting is because of Short-circuit_evaluation.

  • OR : Evaluation stops on first operand which is true and true is returned
  • AND : Evaluation stops on first operand which is false and false is returned
  • Mcpeak answered 4/8, 2012 at 6:5 Comment(4)
    I just tried this, this will still redirect to action="checked.html" after it checks all the functions in validateForm()Effectually
    Updated answer with slightly changed example code and working jsfilddle example. Can you test now?Mcpeak
    No, it's not lazy evaluation, it's short circuiting. en.wikipedia.org/wiki/Short-circuit_evaluationCursive
    Ahh, you are right... Seems I had learnt something wrong, something learned todayMcpeak
    O
    1

    Following method check first validateName() function and it will process to check next function if only first function is true, also to fire third function need to return true of first & second function. So just imagine if all function are invalid & even you have different error message, you will see only error message of first function. Once validateName() function pass, you may see the error message of validatePhone() ect.

    <form id="myForm" name="myForm" action="checked.html" method="post"
    onsubmit="return (validateName() && validatePhone() && validateAddress() &&
    validateEmail() )">
    

    You can't use above if you going to show error messages according to above all validations on first submit & you can use following method if you want to fire all function (or display all validation errors) on submit.

    <form id="myForm" name="myForm" action="checked.html" method="post"
    onsubmit=" if( ( validateName() && validatePhone() && validateAddress() &&
    validateEmail() ) == false) { return false; } ">
    
    Oilstone answered 19/7, 2017 at 10:16 Comment(0)
    J
    0

    onsubmit="return validateName() && validatePhone() && validateAddress() && validateEmail()"

    use this code

    Jalap answered 9/5, 2014 at 11:24 Comment(0)
    C
    0

    To validate my form I simply created a function called validateForm(){} then inside this function I put all the code which is needed for full validation. Then used onsubmit="validateForm()". It checks through it in order and only submits if all conditions are true.

    Codicodices answered 18/12, 2014 at 5:17 Comment(0)

    © 2022 - 2024 — McMap. All rights reserved.