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?

1

2 Answers 2

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}$/;
Sign up to request clarification or add additional context in comments.

2 Comments

now i got the problem that the email isnt valid also when its a real email adress
Follow the link in my comment to your question for other/better expressions to validate addresses. Also: only one question per question ;-)
1

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

emailRegex = /hogehoge/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.