Search code examples
jqueryformsform-submitemail-verificationhtml-formhandler

How to force user to enter a valid email and not let them click on submit button otherwise?


I am curious how I can force the user to enter a valid email address and if it is not valid don't show the submit button as active?

here's the current code I have. Currently if the email is invalid, it shows a red border but still the user can click on the submit button.

$("button[type='submit']").on('click', function () {

        $(".error").hide();
        let hasError = false;

        let emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

        let emailAddressVal = $("#user_email").val();
        if (emailAddressVal == ''){
            $("#user_email").after('<span class="error">Please enter your email address.</span>');
            hasError = true;
        }

        else if(!emailReg.test(emailAddressVal)) {
            $("#user_email").after('<span class="error">Enter a valid email address.</span>');
            hasError = true;
        }

        //alert(emailAddressVal);

        if(hasError == true) {
            return false;
        }


    })

Here's where the input is entered:

        <div class="col-md-3">
            <i class="fas fa-envelope fa-lg"></i>
            <label data-error="wrong" data-success="right">Enter your email</label>
            <input type="email" class="form-control validate purple-border" id="user_email">

        </div>

And here's the submit button:

<button type="submit" class="btn btn-purple purple-border">Perform Frame Classification</button>

enter image description here


Solution

  • Rather than using a click event on the submit button to check the email, check it as the user types (on keyup event), and use the result of the test to enable the button (note that we start with the button disabled):

    $("#user_email").on('keyup', function() {
      $(".error").hide();
      let hasError = false;
    
      let emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    
      let emailAddressVal = $(this).val();
      if (emailAddressVal == '') {
        $("#user_email").after('<span class="error">Please enter your email address.</span>');
        hasError = true;
      } 
      else if (!emailReg.test(emailAddressVal)) {
        $("#user_email").after('<span class="error">Enter a valid email address.</span>');
        hasError = true;
      }
    
      $('button[type="submit"]').prop('disabled', hasError);
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="col-md-3">
      <i class="fas fa-envelope fa-lg"></i>
      <label data-error="wrong" data-success="right">Enter your email</label>
      <input type="email" class="form-control validate purple-border" id="user_email">
    
    </div>
    
    
    <button type="submit" class="btn btn-purple purple-border" disabled="disabled">Perform Frame Classification</button>