user3192948
user3192948

Reputation: 251

jQuery Check user's input before form submission

I'm trying to validate user's input before they submit the form. Although I'm successful doing so when they hit the button, somehow I couldn't make it also stop when they press the enter key:

HTML:

   <form method='post' class='submit_form' action="<?php echo base_url();?>interview/reserve_temporary">
        <input type="text" class="form-control email_input" id="reserve_email_2" placeholder="Email">
        <button type="button" id="subscribe_2" class="btn btn-default text-center foot-submit-btn subscribe_button">Let me try</button>
   </form>

JS:

  $('.submit_form').submit(function(e) { 

      var email = $(this).find('.email_input').val();
      var id=$(this).find('.subscribe_button').attr('id').split("_").pop(); 

      var regex_email = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

      if (regex_email.test(email)||email.match(/^\d+$/)) {
          $(this).text('Sending……');
      }
      else {
          return false;
      }
 } 

Upvotes: 2

Views: 1110

Answers (2)

Lawrence Johnson
Lawrence Johnson

Reputation: 4043

Give this a shot:

$('.submit_form').submit(function(e) { 

    var email = $(this).find('.email_input').val();
    var id=$(this).find('.subscribe_button').attr('id').split("_").pop(); 

    var regex_email = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    if (regex_email.test(email)||email.match(/^\d+$/)) {
        $(this).text('Sending……');
        return true
    }
    else {
        e.preventDefault();
        e.stopImmediatePropagation();
        return false;
    }
} 

Upvotes: 2

Mohamed Amin
Mohamed Amin

Reputation: 1067

you can use a more easy option to validate your inputs check jquery validation engine ,an easy&powerful validation tool https://github.com/posabsolute/jQuery-Validation-Engine

Upvotes: 0

Related Questions