Sergei R
Sergei R

Reputation: 721

jQuery Validation Plugin this.optional is not a function

I create a custom validation. In the docs I found method addMethod()

My example:

Template.Login.onRendered(() => {
  jQuery.validator.addMethod('strongPassword', (value, element) => {
    return this.optional(element)
      || value.length >= 6
      && /\d/.test(value)
      && /[a-z]/i.test(value);
  }, 'Your password must be at least 6 characters long and contain at least one number and one char.');

$('.login-form').validate({
    rules: {
      password: {
        required: true,
        strongPassword: true
      }
    }
  });
});

And I get error:

_this.optional is not a function. Exception occurred when checking element , check the 'strongPassword' method.

That is my issue?

Upvotes: 2

Views: 1283

Answers (2)

Rylee
Rylee

Reputation: 1656

I know this is an old question but I recently ran into this issue after converting code to ES6.

Standard:

this.optional(element)

ES6:

$.validator.prototype.optional(element)

Upvotes: 2

Suren Srapyan
Suren Srapyan

Reputation: 68665

The issue is related to this. When you use arrow functions (you have 2 cases there) the this refers to the upper one's div context, in your case is the this where onRendered has been called. Change arrow function into simple function to get the appropriate this context.

jQuery.validator.addMethod('strongPassword', function (value, element) {
    return this.optional(element)
      || value.length >= 6
      && /\d/.test(value)
      && /[a-z]/i.test(value);
  }, 'Your password must be at least 6 characters long and contain at least one number and one char.');

Upvotes: 3

Related Questions