0

I have three email forms on one page, all using the same class. When someone enters an email address and submits one of those forms, I want to validate the email address entered into that specific form. The problem that I'm having if is someone enters an email address for one of the later forms, it validates against the data in the first form. How can I make it so my validation function validates for the field into which the email address was entered without having to give each form a unique ID and have the validation code multiple times?

The validation code is below and code for one of the forms. Thanks!

               <script>
                    function validateMyForm() {
                            var sEmail = $('.one-field-pardot-form-handler').val();
                            if ($.trim(sEmail).length == 0) {
                                event.preventDefault();
                                alert('Please enter valid email address.');
                                return false;

                            }

                            if (validateEmail(sEmail)) {

                            }

                            else {
                                event.preventDefault();
                                alert('Invalid Email Address. Please try again.');                          }
                    };

                    function validateEmail(sEmail) {
                        var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
                        if (filter.test(sEmail)) {
                            return true;
                        }
                        else {
                            return false;
                        }
                    }                                                  

                 </script>  

                 <form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" onSubmit="return validateMyForm();" novalidate>

                    <input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
                    <div style="position:absolute; left:-9999px; top: -9999px;">
                      <label for="pardot_extra_field">Comments</label>
                      <input type="text" id="pardot_extra_field" name="pardot_extra_field">
                    </div>

                    <button type="submit" name="submit">Submit</button>
                </form>
dpayne
  • 273
  • 3
  • 14
  • Can't you check for which input has a value in it and then validate it's parent form? Or validate each form that has a value in it's input when submitted (if a user could enter emails into more than one form)? – Steve Oct 25 '17 at 22:11

3 Answers3

1

Rather than calling the method from the html onsubmit attribute, wire the whole thing up in jquery.

$('form.myform').submit(function(e){
   var $theForm = $(this);
   var $theEmailInput = $theForm.find('.one-field-pardot-form-handler');
   validateEmail($theEmailInput.val());
});
Paul
  • 35,689
  • 11
  • 93
  • 122
  • instead of `var theForm = $(this); var theEmailInput = theForm.find('.one-field-pardot-form-handler');` you can write `var theEmailInput = $('.one-field-pardot-form-handler', this);` – Joshua K Oct 25 '17 at 22:17
  • @JoshuaK sure, I was trying to be explicit since the OP seems newbish. – Paul Oct 25 '17 at 22:18
  • Ok. Some "improvement": In conformance to the jquery naming convention it should be `$theForm` and `$theEmailInput`. For a newbie it's a good memory prop to prepend all jQuery collections with a $ sign. – Joshua K Oct 25 '17 at 22:23
  • I've literally never heard that before, nor seen it in any example code. And I've used jquery since... well, before it was on a CDN. – Paul Oct 25 '17 at 22:26
  • 1
    @Paul It's a very common convention that's been around, well since before JQuery was on a CDN. – Scott Marcus Oct 25 '17 at 22:30
  • 1
    @Paul Here's a **[SO post](https://stackoverflow.com/questions/205853/why-would-a-javascript-variable-start-with-a-dollar-sign)** from 2009. – Scott Marcus Oct 25 '17 at 22:41
1

If you have 3 forms, just target the email field (via the class) within the context of the form.

And, don't use inline HTML event attributes (onsubmit, etc.), there are many reasons why and you can read about those here. Instead, do all your event binding with JavaScript/JQuery and then you won't need to worry about return false to cancel the event if you are already using .preventDefault(). Additionally, it's best to capture the event reference as an argument to the event callback function, instead of the global event object.

There were other items that should be adjusted as well, so see additional comments inline:

// Get all the form elements and set up their event handlers in JavaScript, not HTML
$("form").on("submit", validateMyForm);

function validateMyForm(evt) {
  // First, get the form that is being filled out
  var frm = evt.target;
  evt.preventDefault();
  
  // Now, just supply the form reference as context for the email search
  // Notice the extra argument after the selector "frm"? That tells JQuery
  // where within the DOM tree to search for the element.
  var sEmail = $('.one-field-pardot-form-handler', frm).val();
  
  // Just to show that we've got the right field:
  $('.one-field-pardot-form-handler', frm).css("background-color", "yellow");
  // ***************************************************************************
  
  // No need to convert a string to a JQuery object and call .trim() on it
  // when native JavaScript has a .trim() string method:
  if (sEmail.trim().length == 0) {
    evt.preventDefault();
    alert('Please enter valid email address.');
  }

  // Don't have empty branches, reverse the logic to avoid that
  if (!validateEmail(sEmail)) {
    evt.preventDefault();
    alert('Invalid Email Address. Please try again.');                         
  }

}

function validateEmail(sEmail) {
  var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
  
  return filter.test(sEmail);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" 
      method="post" 
      novalidate>
  <input class="one-field-pardot-form-handler" 
         maxlength="80" 
         name="email" 
         size="20" 
         type="email" 
         placeholder="Enter Email Address" 
         required>
  <div style="position:absolute; left:-9999px; top: -9999px;">
    <label for="pardot_extra_field">Comments</label>
    <input type="text" id="pardot_extra_field" name="pardot_extra_field">
  </div>

  <button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" 
      method="post" 
      novalidate>
  <input class="one-field-pardot-form-handler" 
         maxlength="80" 
         name="email" 
         size="20" 
         type="email" 
         placeholder="Enter Email Address" 
         required>
  <div style="position:absolute; left:-9999px; top: -9999px;">
    <label for="pardot_extra_field">Comments</label>
    <input type="text" id="pardot_extra_field" name="pardot_extra_field">
  </div>

  <button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" 
      method="post" 
      novalidate>
  <input class="one-field-pardot-form-handler" 
         maxlength="80" 
         name="email" 
         size="20" 
         type="email" 
         placeholder="Enter Email Address" 
         required>
  <div style="position:absolute; left:-9999px; top: -9999px;">
    <label for="pardot_extra_field">Comments</label>
    <input type="text" id="pardot_extra_field" name="pardot_extra_field">
  </div>

  <button type="submit" name="submit">Submit</button>
</form>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/157527/discussion-on-answer-by-scott-marcus-how-to-validate-an-email-submission-form-wh). – Andy Oct 26 '17 at 01:02
0

So a combination of @paul and @ScottMarcus' answers above ultimately got me to where I needed to go. Below is what I ended up with and it works as intended. As others have pointed out, I'm definitely a n00b and just learning javascript so certainly may not be perfect:

<script>
$('form.pardot-email-form-handler').submit(function(event) {
var theForm = $(this);
var theEmailInput = theForm.find('.one-field-pardot-form-handler');
var theEmailValue = theEmailInput.val();

function validateEmail(theEmailValue) {
var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(theEmailValue)) {
return true;
} else {
return false;
}
}

if (!validateEmail(theEmailValue)) {
event.preventDefault();
alert('Invalid Email Address. Please try again.');
} else {
return true;
}

});
</script>
<div class="nav-email-form">    
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" class="pardot-email-form-handler" novalidate>

<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>

<button type="submit" name="submit">Submit</button>
</form>

</div>
dpayne
  • 273
  • 3
  • 14