Question

I'm trying to validate email upon submit. Right now, I have it working so that it validates if I tab from the email to submit button, and also if I click the submit button directly. However, it doesn't validate if I press Enter from within the email field. Also, once it validates on clicking submit, I have to click the button again to actually submit.

The reason is because I start with type="button" rather than type="submit" on the submit input. This is because before when I started with type="submit" it would submit regardless of whether the email was valid or not.

So now, I start with type="button", validate the email, and then change it to type="submit" on valid emails. However, like I mentioned, it still isn't the most user-friendly (even though it does work as is). I'd like to add the user-friendly features described above. Here is the code I have (note: I'm using the Mailgun jQuery email validator for the validation part):

<form accept-charset="UTF-8" id="icpsignup" name="icpsignup" action="process.php" method="post">
    <p>                              
     <input type="text" onfocus="this.value=''" onblur="this.value=!this.value?'Enter name...':this.value;" class="txtbox_index" placeholder="Enter name..." value="Enter name..." name="fields_fname" id="fields_fname">
    </p>                                                                                 
    <p>                                            
     <input type="text" class="txtbox_index" onfocus="this.value=''" onblur="this.value=!this.value?'Enter email...':this.value;" name="fields_email" id="fields_email" Value="Enter email..." placeholder="Enter email...">
     <input type="text" style="border: none;color: #fff;cursor: none; background-color:transparent; height:0px;" size="1" value="<?=$country_field;?>" name="fields_country" id="fields_country">
   </p>
     <div id="status"></div>                                            
   <p class="forfree">                                              
     <input type="button" value="Signup For Free!" id="validate_submit" class="signupbtn_new" name="submit">
   </p>
     <input type="hidden" value="<?php echo $paramstring ;?>" name="fields_trk">
</form>   

<script src="js/vendor/jquery.js"></script>
<script src="js/mailgun_validator.js"></script>
<script>
      // document ready
      $(function() {

        // capture all enter and do nothing
       /* $('#fields_email').keypress(function(e) {
          if(e.which == 13) {
            $('#fields_email').trigger('focusout');
            return false;
          }
        });

        // capture clicks on validate and do nothing
       /* $("#validate_submit").click(function() {
          return false;
        });*/

        // attach jquery plugin to validate address
        $('#fields_email').mailgun_validator({
          api_key: 'pubkey-8s-e-ovj0nbi32xw5eeyibrmv-lkq2e2', // replace this with your Mailgun public API key
          in_progress: validation_in_progress,
          success: validation_success,
          error: validation_error,
        });

      });



      // while the lookup is performing
      function validation_in_progress() {
        $('#status').html("<img src='images/loading.gif' height='16'/>");
      }



      // if email successfull validated
      function validation_success(data) {
        $('#status').html(get_suggestion_str(data['is_valid'], data['did_you_mean']));
      }



      // if email is invalid
      function validation_error(error_message) {
        $('#status').html(error_message);
      }



      // suggest a valid email

 submitHandler: function(form) {
      function get_suggestion_str(is_valid, alternate) {
        if (alternate) {
          form.preventDefault();
          return '<span class="warning">Did you mean <em>' + alternate + '</em>?</span>';
        } else if (is_valid) {
          form.submit();
          //return '<span class="success">Address is valid.</span>';
        } else {
          form.preventDefault();     
          return '<span class="error">Address is invalid.</span>';
        }
      }
}

// Another version of trying to using the Submithandler. I'm not sure if I'm supposed to use the validate or not.:

$(function() {
  $("#icpsignup").validate({
 submitHandler: function('icpsignup') {
      function get_suggestion_str(is_valid, alternate) {
        if (alternate) {
          icpsignup.preventDefault();
          return '<span class="warning">Did you mean <em>' + alternate + '</em>?</span>';
        } else if (is_valid) {
          icpsignup.submit();
          //return '<span class="success">Address is valid.</span>';
        } else {
          icpsignup.preventDefault();     
          return '<span class="error">Address is invalid.</span>';
        }
      }}
    })
})


    </script>
Was it helpful?

Solution

UPDATE: A MORE complete answer:

NOTE: this assumes you will be using jQuery 1.4.3 or higher


The SUBMIT event is sent to an element when the user is attempting to submit a FORM:

  • It can only be attached to <form> elements.
  • Forms can be submitted either by clicking an explicit:

    • <input type="submit">,
    • <input type="image">, or
    • <button type="submit">,
      or
    • by pressing Enter when certain form elements have focus.


      NOTE: *Depending on the browser, Enter may only cause a form submission if:

      • the form has exactly one text field, or
      • only when there is a submit button present.


        Therefore, your code shouldn't rely on a particular behavior for this key unless the issue is forced by observing the keypress event for presses of the Enter key which is character code 13.

        • Here is information about how to use the .keypress() handler from jQuery.com
        • Here is a chart comparing all ASCII character/key codes, HTML escape codes, and they keys/character they represent.

You can get more detailed information at the jQuery.com site .submit() page HERE.


In your scenario (and most), I would use a <input type="submit"> button and capture the SUBMIT event.

In the submit handler callback function:

$( "form#icpsignup" ).submit(function( evt ){
  //...
  $('#fields_email').mailgun_validator({
    api_key: 'pubkey-8s-e-ovj0nbi32xw5eeyibrmv-lkq2e2', // replace this with your Mailgun public API key
    in_progress: validation_in_progress,
    success: validation_success,
    error: validation_error,
  });
  //...
}

You will need to validate your <form> (i.e. use whatever code, statement, etc. on one or more input fields). Then upon...

  • success - use a return true statement
  • failure - use an evt.preventDefault(); where evt is the argument passed to your submit handler.

.

Below is a detailed example:


<!doctype html> 
<html lang="en">

  <head>   
    <meta charset="utf-8">  
    <title>submit demo</title>   
    <style>   
      p {
        margin: 0;
        color: blue;
      }
      div,p {
        margin-left: 10px;   
      }   
      span {
        color: red;   
      }   
    </style>   
    <script src="//code.jquery.com/jquery-1.10.2.js"></script> 
  </head> 

  <body>  
    <p>Type 'correct' to validate.</p> 
    <form action="javascript:alert('success!');"
      <div>
        <input type="text">
        <input type="submit">   
      </div> 
    </form> 

    <script> 

      // "function( evt )" is an anonymous function.  It *is* your handler
      $( "form" ).submit(function( evt ) {   // evt is the *event* object. 
                                             // name it whatever you'd like. 
        if ( $( "input:first" ).val() === "correct" ) {  
          $( "span" ).text( "Validated..." ).show();
          return true;   
        }
        $( "span" ).text( "Not valid!" ).show().fadeOut( 1000 );
        evt.preventDefault(); 
      }); 
    </script>

  </body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top