Jump to content
Larry Ullman's Book Forums

Embedded Function Return False - Does It Reach Outer Form Onsubmit?


Recommended Posts

Hello, everyone!  Please kindly note that I have an event call for form onsubmit.  However, the return false to prevent default behavior of the form submission is embedded two functions below, and I'm not sure if it will reach the theform.onsubmit function call.  Please help.

 

Here is the original form onsubit function call:

   var theform = document.getElementById('registerForm');

    theform.onsubmit = validateFormOnSubmit;

 

It then goes to a function that checks each field like this,

 

                function validateFormOnSubmit() {

// FIRSTNAME field validation with the errorMessage brackets escaped

                regularExpressionMatchFunction("firstName", /^[A-Za-z'\.]+\s*[A-Za-z'\.\s]*$/, "The name must include alphabetical letters \(and can include apostrophes, periods, and spaces\)");

               

// VALIDATE LAST NAME

                //This code validates lastName with some text boxes initially implemented to ensure code works properly.

                // HTML5FieldCheck is not needed here as there is no default text in the lastName field.

                regularExpressionMatchFunction("lastName", /^[A-Za-z'\.]+\s*[A-Za-z'\.\s]*$/, "The name must include alphabetical letters \(and can include apostrophes, periods, and spaces\)");

 

And so forth.  The regular expressionMatch Function above then calls a function that I set a flag variable in and that checks to see if there is a regular expression match.  If the regular expression does or does not match, there is a remove error message and add error message command, respectively.  If the code demands that an error message be added, I have set the flagVariableError to false and then follow the function by returning the flag varialble.

 

var flagVariableNoError = true;

 

etc., etc.,

 

if (finalRegExpressBooleanFieldName == true) {

                                //removeErrorMessage inserted here will take the element by id field but not an error message as arguments

                                removeErrorMessage(id);

                                alert("You are an awesome coder!");

                }

                else {

                                // addErrorMessage will take the getElementById field "firstName" and also the error message text (the above parameter) as arguments

                                addErrorMessage(id, errorMessageText);

                                // The return false code didn't work in the addErrorMessage function itself, so I'll try it here

                                flagVariableNoError = false;

                }

                // This is returning the value of the flagVariableNoError to the form submission event

                if (flagVariableNoError = false) {

                                return false;

                }

I am not sure that the return false will be recognized by the first form onsubmit calling function at the very top.  I believe this is so because the return false command is embedded two functions down, and I'm not sure how to get it to reach the top function: namely, the form onsubmit function at the top here.

 

Please advise!

Link to comment
Share on other sites

I'm having a lot of trouble following your code.

I think it would help if you used the <> button in the editor to better format and color code everything.

 

As a general answer to your question though, you can either pass back true/false from the subfunctions to the main function and return that, or you can have an independent Boolean, whose value is calculated based on some sort of condition(s).

 

I know that probably doesn't help much, but without cleaning up your code more, there isn't much we can do to help.

Link to comment
Share on other sites

Thanks, HartleySans!  Your help is always appreciated!  I cleaned up my code more, and here is the next attempt!  I am wondering how I can get the return false in the third layer of embedded functions to reach the first to prevent the default behavior of onsubmit for the form.  I highlighted the return false and the original calling function both in bold.  Thanks so much in advance for any and all help!

 

function regularExpressionMatchFunction(id, regularExpressionMatch, errorMessageText) {

                //declare variables used in field check.

                alert("At beginning of function, the regular expression is " + regularExpressionMatch);

                var flagVariableNoError = true;

                var fieldName;

                var fieldNameValue

                var regExFieldName

                var finalRegExpressBooleanFieldName

                var fieldNameValueTrimmed

                // Get field name and field value

                fieldName = document.getElementById(id);

                fieldNameValue = fieldName.value;

                // TRIM WHITE SPACE Function Called here

                fieldNameValueTrimmed = trimWhiteSpace(fieldNameValue);

                alert("My fieldNameValueTrimmed is" + fieldNameValueTrimmed);

                finalRegExpressBooleanFieldName = regularExpressionMatch.test(fieldNameValueTrimmed);

                alert("After doing regular expression MATCH, the value of      finalRegExpressBooleanFieldName (the boolean) is " + finalRegExpressBooleanFieldName);

                if (finalRegExpressBooleanFieldName == true) {

                                removeErrorMessage(id);

                                alert("You are an awesome coder!");

                }

                else {

                                addErrorMessage(id, errorMessageText);

                                flagVariableNoError = false;

                }

                if (flagVariableNoError = false) {

                                return false;

                }

}

 

function validateFormOnSubmit() {

                // FIRSTNAME field validation

                regularExpressionMatchFunction("firstName", /^[A-Za-z'\.]+\s*[A-Za-z'\.\s]*$/, "The name must include alphabetical letters \(and can include apostrophes, periods, and spaces\)");

               

                // VALIDATE LAST NAME

                regularExpressionMatchFunction("lastName", /^[A-Za-z'\.]+\s*[A-Za-z'\.\s]*$/,

"The name must include alphabetical letters \(and can include apostrophes, periods, and spaces\)");

 

                // VALIDATE EMAIL

                regularExpressionMatchFunction("email", /^[\w.-]+@[\w.-]+\.([A-Za-z]{2,6})+/,
"A valid email address is required");

               

                // VALIDATE TELEPHONE

                regularExpressionMatchFunction("telephone", /^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)?\d{4}$/,                 "Please enter the phone number in any of a variety of formats, including xxx-xxx-xxxx,                  \(xxx\)xxx-xxxx, \(xxx\) xxx-xxxxx, xxxxxxxxxx, xxx xxx xxxx")

                // VALIDATE COMPANY NAME 

                regularExpressionMatchFunction("companyName", /^[\w'.&]*\s*[\w'&\s]*$/, "Company names                 can only contain alphabetical letters, numbers, underscores, '&', and apostrophes");

               

                // VALIDATE COUNTRY NAME   

                regularExpressionMatchFunction("country", /^[A-Za-z'\.]+\s*[A-Za-z'\.\s]*$/, "Country
name can only contain letters, periods, apostrophes, and spaces");

}

 

function init(){

    var theform = document.getElementById('registerForm');

    theform.onsubmit = validateFormOnSubmit;

    var retypeEmailField = document.getElementById('retypeEmail');  // This is my own coding idea

    retypeEmailField.onblur = validateEmailMatch;

}

Link to comment
Share on other sites

angels, please use the <> button in the site editor to mark your code. Your code is still hard to read.

 

Anyway, as a general solution, I would first always return flagVariableNoError from the regularExpressionMatchFunction function, regardless of whether it is true or false.

I would then have that return value stored in an array of return values. For example, at the top of the validateFormOnSubmit function, define a new variable as such:

var returnVals = [];

Then, store each of the values returned by the regularExpressionMatchFunction function calls in the array like so:

returnVals.push(regularExpressionMatchFunction("firstName", /^[A-Za-z'\.]+\s*[A-Za-z'\.\s]*$/, "The name must include alphabetical letters \(and can include apostrophes, periods, and spaces\)"));

Then, after all the regularExpressionMatchFunction function calls are complete, do something like the following:

for (var i = 0, len = returnVals.length; i < len; i += 1) {
  if (!returnVals[i]) {
    return false;
  }
}
 
That answer your question?
  • Upvote 1
Link to comment
Share on other sites

That is the most awesome answer I could have hoped for!  Wow!  Thanks so much, HartleySans!  You are the MAST-AH!!  (Larry, too, of course!)

 

Whew!!  One quick question from a very amateurish starting point, if I use

returnVals.push(regularExpressionMatchFunction("firstName", /^[A-Za-z'\.]+\s*[A-Za-z'\.\s]*$/, "The name must include alphabetical letters \(and can include apostrophes, periods, and spaces\)"));

will regularExpressionMatchFunction automatically execute? 

 

Thanks for the tip on getting my code to work well in the forum, too, my friend!

 

God bless you!!  You saved me hours of defeat and torment!  Thank you so very much!

Link to comment
Share on other sites

It won't "automatically" execute, per se, but it will execute because you have the parentheses after the function name.

Any time you put parentheses after a function name, the function will be called. The only difference from my code and yours is that the return value of the regularExpressionMatchFunction function is then sent as an argument to the push method of the returnVals array (in one line of code).

You could, of course, pull the code out across a couple of lines for clarity's sake, but I really don't think it necessary in this case.

 

Also, I'm more than happy to help, but I would recommend a couple of things in the future:

  1. Try not to rely on me and this forum too much. Really, really try to do things yourself before coming here. It's not that we don't want you here; it's more that I think you'll grow more as a programmer if you try more to solve problems you encounter yourself. Sure, it can certainly be frustrating (believe me, I know), but I think maybe giving problems you face a little more time yourself before coming on here will help you grow.
  2. Please make more of a concerted effort to clearly explain any problems you're having and provide legible code snippets in your posts. Whenever I make a post asking for help here or on Stack Overflow, etc., I always re-read my post many times and edit it accordingly before actually posting it to make it as simple and straightforward as possible for anyone that may potentially help me. Doing so will make it much more likely that people will in fact try to help you.

 

Anyway, I'm glad you solved your problem!

  • Upvote 1
Link to comment
Share on other sites

Hi HartleySans!  I hear you!  I really needed to learn the ropes of submitting on a forum as this is really my first venture out into the area.  Thanks so much for the advice!

 

I implemented the code, and it worked like a charm!  Thank you so very much.  Truthfully, I'm not sure if I would have stumbled on such an elegant solution if I had just searched the Web for solutions, but I guess banging my head against the wall for weeks on end is a good growth opportunity for me! : )

 

Thank you so very much for the excellent advice and God bless!

Link to comment
Share on other sites

 Share

×
×
  • Create New...