Validate email using jQuery

I have a problem verifying email address with script below, its not working even if i enter correct email format, it doesn’t move to next hidden div

first i want to do empty-check and then validate if entered email is in good format

<script>
        $('#fobtn').click(function(){
        var email = $('#email').val();
        var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if( !$(this).val() ) {
          $("#error").html("email needed cant leave this blank");
          return false;
    } 
    
    
        if(!regex.test(email)) {
           $("#error").html("valid email needed");
           return false;
        }
      
    
    else{
  $('#hidden1').hide();
  $('#hidden2').show();
  }
  
});
</script>

Wouldn’t just:

<input type="email" placeholder="Enter email address" required>

accomplish the validation need, then you can do your show/hide simply on whether they typed something in the email field?

3 Likes

i know this type=“email”, but i have a reason why i decided to go with that way

@Craig20001x, i know this type=“email”, but i have a reason why i decided to go with that way

Firstly it would be helpful if you could share that reason. It would take the guesswork out of it for people trying to assist.

Secondly it would be useful to see the html form that goes with this.

It may well be that there is a pure HTML/CSS solution to your problem (Frontend anyway). Don’t forget inputs also have a pattern attribute where you can specify a regex. CSS has :invalid and :valid pseudo selectors and even the new :user-valid selectors.

Lastly I don’t see the need for two separate email validations e.g. blank and valid. I would keep it simple and just use the ‘valid email needed’ for both scenarios.

1 Like

Insert standard response of ‘define valid’.

john@notareal.academy would like a word with your regex, as would "thisis..alegitimate"@mail.com, or maillist!johnsmith@uucpmail.com, or…

(Trying to create a regex that actually encompasses the RFC6854 standard is annoyingly difficult, is the point.)

3 Likes

Which is why everyone advises type="email" to check the email and required to reject a blank input, both of which are very easy to do.
I can’t think of any reason why you would not choose this easy, effective method.

4 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.