0

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>
programmingnewb
  • 129
  • 2
  • 9

1 Answers1

0

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>
Flak DiNenno
  • 2,193
  • 4
  • 30
  • 57
  • 1
    Thanks Flak, I've added a submit handler as you suggest. Does it look like I did it in the right place and correct way? – programmingnewb May 07 '14 at 18:56
  • 1 sec.. let me check this out – Flak DiNenno May 07 '14 at 19:21
  • Where did you get this mailgun validator from? – Flak DiNenno May 07 '14 at 19:26
  • 1
    is it long? can you post it... rather.. I will give you some sample validation code and you can replace it later – Flak DiNenno May 07 '14 at 19:26
  • 1
    @programmingnewb I just updated with a ton of info... hopefully that clears it all up for you – Flak DiNenno May 07 '14 at 20:29
  • Hi Flak, thanks for all the help. I got the mailgun script from here: https://github.com/mailgun/validator-demo/ – programmingnewb May 07 '14 at 20:51
  • I'm updating their jquery plugin for use on an actual submit form. – programmingnewb May 07 '14 at 20:51
  • I've read through the jQuery example you posted above on the jQuery.com site. I'm not sure that gets me closer to actually implementing the Mailgun jQuery validator on my form. I was really close with the code I already had, just had those couple of errors I mentioned. I'm still not sure what to do to fix them. – programmingnewb May 07 '14 at 20:53
  • you want to replace the code in my example to a call to the Mailgun validator – Flak DiNenno May 07 '14 at 21:29
  • @programmingnewb I just edited my answer again and inserted references to your form and inserted the mailgun validator into the handler... in the first code block, before the long example. check it ouit. – Flak DiNenno May 07 '14 at 21:36
  • I chose yours as the best answer since it obviously is. However, I still haven't been able to get it to work. Definitely trying (for three days now), but I'm about to have to give up unfortunately. I guess I just don't understand exactly how to actually implement these things in my code. This is what I produced with what you said, but it's not working:http://codeshare.io/WtzWu I wrapped all the functions in a submit handler. Again, thanks for all the help, and I don't expect more. I may just have to use the non-user friendly version and pay a pro eventually. – programmingnewb May 08 '14 at 16:08