Email regex not validating properly after first validation

Email regex not validating properly after first validation


I'm setting up some custom validation for a form (not using a plugin as I want to force myself to learn). But this problem is stumping me a little, I was wondering if you can help?

I have searched on this site but haven't been able to find a thread on this specific issue.

The email validation works first time. So if I leave the field empty, or enter a, or enter a@, or enter a@a it will show the error message specified.

Once I enter a valid email address, as expected the error message disappears.

This is where it gets funky. I then decide to make the email address invalid again by removing the @ symbol. I try to submit the form, expecting the error message to re-appear but it doesn't.

Instead, Opera adds a fuzzy border around the email input. So it's like the browser is still validating but my error message is not being displayed.

The same occurs if I make the email address invalid via the other methods listed above.

If I delete all the characters from the email input, I see the error message again until I enter a valid email address.

I've tried about 5 different email regexes and I get the same issue. Is it my code? Or the browser??

Thank you.

  1. $('form[name="myForm"]').submit(function(event) {
  2. $.fn.stopForm = function() {
  3. event.preventDefault();
  4. if ($(this).next('.error').length == 0) {
  5. $(this).after('<div class="error"></div>');
  6. }
  7. }
  8. $('.required').each(function() {
  9. //Check Subject
  10. if ($(this).attr('id') == 'subject' && $(this).val().length == 0) {
  11. $(this).stopForm();
  12. $(this).next('.error').html('Please select a subject.');
  13. }

  14. //Check Name
  15. else if ($(this).attr('id') == 'name' && !$(this).val().trim().match(/[A-z]|'|-|./)) {
  16. $(this).stopForm();
  17. $(this).next('.error').html('Please enter a valid name \(letters, apostrophies, dashes and dots only\).');
  18. }

  19. //Check Email
  20. else if ($(this).attr('id') == 'email' && !$(this).val().match(/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/)) {
  21. $(this).stopForm();
  22. $(this).next('.error').html('Please enter a valid email address.');
  23. }
  24. else {
  25. $(this).next('.error').remove();
  26. event.preventDefault();
  27. }
  28. });
  29. });