0

I'm just making some form validation with jQuery, this is the part for the email:

var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var email = $('#user_email');
$('#user_email').on('keyup change', function() {
      if ((email.val().length <= 6) && (re.test(email.val()))) {
        $('#alert_user_email').text('Email cannot be blank or invalid formation');
        submit_btn.disabled = true;
        $('#alert_user_email').show();
      } else {
        $('#alert_user_email').text('');
        submit_btn.disabled = false;
        $('#alert_user_email').hide();
      }
    });

But for some reason it isn't working, everything works fine if I remove the && re.teststuff from the if statement but isn't working as intended, any enlightenment would be great!

Datsik
  • 14,453
  • 14
  • 80
  • 121
  • "but isn't working as intended" What is it doing then? – Iron3eagle Apr 05 '13 at 21:09
  • Have you tried validating your regex? – jahroy Apr 05 '13 at 21:10
  • 3
    e-mail validation on the clientside never works as intended. Just do a really basic search for @, and a period, and do the rest on the serverside. – adeneo Apr 05 '13 at 21:11
  • 1
    @jahroy yes it works great on the node.js server side of things. – Datsik Apr 05 '13 at 21:11
  • Just as an added thing on top of Intelekshual's answer below, theres not much point marking the $('#alert_user_email') to be blank you might as well have the text pre-written in the HTML and then just use the hide and show. Just a bit faster and what you have I'm pretty sure is completely needless unless you need it for the server side (which I doubt) but ontop of adeneo's comment. It is wise to have server side validation as well it's not that it doesn't work but more that people can amend your code via things like console and make the validation not actually work. – Nick White Apr 05 '13 at 21:22

1 Answers1

5

Your if statement is incorrect. Try:

if ((email.val().length <= 6) || !(re.test(email.val()))) {
    // your code
}
Intelekshual
  • 7,444
  • 1
  • 21
  • 28
  • Thanks for this, but while I was awaiting a response I switched it to type='email' and now the browser seems to automatically validate my email for me, but do you know how I can set a p elements text based on the typed in email? I want to set the submit button to disabled while the HTML5 validation is false – Datsik Apr 05 '13 at 21:26
  • @XCritics If you're going to use HTML5 validation, you can listen for the 'invalid' event on submit, or call `checkValidity()` directly. See [this answer](http://stackoverflow.com/a/7587778/127769) for more details. – Intelekshual Apr 05 '13 at 21:34