Marius
Marius

Reputation: 1281

Uncaught TypeError: obj.attr is not a function JS

I have the following code:

<input type="text" name="email" id="email" class="required-input" value="[email protected]">
function validate(obj) {
    const email_regex = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
    if (obj.attr("id") == "email") {
        regex = email_regex;
    }

    (!obj.val().match(regex) || obj.val().length == 0 || obj.val() == '') ? obj.removeClass('valid').addClass('invalid'): obj.removeClass('invalid').addClass('valid');
}

$('.required-input').each(function() {
    $(this).on('input keyup keypress blur change', function() {
         validate(this);   //EROR HERE
    });
});

The error is as follows Uncaught TypeError: obj.attr is not a function

Do you know the origin of this error? It is wrong parameter function validated?

Please can you help me solve this problem?

Thanks in advance!

Upvotes: 0

Views: 852

Answers (2)

Satpal
Satpal

Reputation: 133413

As obj is native DOM object you are getting the error. Convert it to jQuery object

$(obj).attr("id")

OR, Better pass jQuery object to validate function.

validate($(this));

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337620

this is a reference to the DOMElement which you're attempting to call jQuery methods on - hence the error. You need to pass a jQuery object to the method instead. Try this:

validate($(this));

Upvotes: 0

Related Questions