2

I'm trying to create a simple validation method with jQuery, but without a plugin. So I made this code:

(function ($) {
  $.fn.validate = function () {
    var emailRegex = '^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$';
    var error = false;
    if ($('#vorname').val() == "") {
      $('#vorname').after('<span class="error">Name fehlt</span>');
      error = "true";
    }
    if ($('#nachname').val() == "") {
      $('#nachname').after('<span class="error">Name fehlt</span>');
      error = "true";
    }
    if ($('#email').val() == "") {
      $('#email').after('<span class="error">Email fehlt</span>');
      error = "true";
    } else if (!emailRegex.test($('#email').val())) {
      $('#email').after('<span class="error">Keine gültige Email</span>');
      error = "true";
    }
    if (error == true) {
      return false;
    } else {
      return;
      true;
    }
  }
})(jQuery);

$(document).ready(function () {
  $('#button').click(function () {
    $('#button').validate();
  });
});

But I'm getting always the message that my regex test isn't a function. What's the issue?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
  • You might find the discussion in question [Validate email address in JavaScript?](http://stackoverflow.com/questions/46155/validate-email-address-in-javascript) interesting as well. – ojdo Apr 10 '14 at 09:21

2 Answers2

3

You write:

var emailRegex = '^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$';

You might want to write:

var emailRegex = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');
// or simpler
var emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
ojdo
  • 8,280
  • 5
  • 37
  • 60
  • now i got the problem that the email isnt valid also when its a real email adress – user3518669 Apr 10 '14 at 09:58
  • Follow the link in my comment to your question for other/better expressions to validate addresses. Also: only one question per question ;-) – ojdo Apr 10 '14 at 10:50
1

Your emailRegex is defined as String. Define it as regexp like this.

emailRegex = /hogehoge/

Kei Minagawa
  • 4,395
  • 3
  • 25
  • 43