[英]jQuery Validation Plugin this.optional is not a function
I create a custom validation.我创建了一个自定义验证。 In the docs I found method addMethod()
在文档中我找到了方法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.
_this.optional 不是函数。 Exception occurred when checking element , check the 'strongPassword' method.
检查 element 时发生异常,请检查“strongPassword”方法。
That is my issue?那是我的问题?
The issue is related to this
.该问题与
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.当您使用箭头函数时(您有 2 种情况),
this
指的是上层的 div 上下文,在您的情况下是this
,其中onRendered
已被调用。 Change arrow function
into simple function to get the appropriate this
context.将
arrow function
更改为简单函数以获得适当的this
上下文。
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.');
I know this is an old question but I recently ran into this issue after converting code to ES6.我知道这是一个老问题,但我最近在将代码转换为 ES6 后遇到了这个问题。
Standard:标准:
this.optional(element)
ES6: ES6:
$.validator.prototype.optional(element)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.