简体   繁体   English

jQuery验证插件始终显示错误消息

[英]jQuery Validation plugin always shows error message

I create custom validation for email checking in the DB. 我为数据库中的电子邮件检查创建自定义验证。

Client: 客户:

Template.Login.onRendered(() => {
  jQuery.validator.addMethod('checkEmailUnique', function(value, element) {
    Meteor.call('checkEmailUnique', value, function(err, result) {
      console.log('Email validator method response: ', result);
      return result;
    )};
  });

  $('.login-form').validate({
  rules: {
      emailAddress: {
        required: true,
        email: true,
        checkEmailUnique: true
      },
  messages: {
     checkEmailUnique: "email found"
      }
  });
});

Server: 服务器:

Meteor.methods({
  // Chech the email to unique
  checkEmailUnique:function(email){
     if(email && Meteor.isServer){
       let foundEmail = Meteor.users.findOne({'emails.address': email});
       if (foundEmail) {
         return false; // fails - display error
       } else {
         return true; // true - no message
       }
     }
  }
});

In the browser console I get message: 在浏览器控制台中,我收到消息:

if email found - false and if email not found - true, but plugin in both cases chow my validation message "email found". 如果找到了电子邮件-否,如果没有找到电子邮件-是,但是在两种情况下,插件都阻止了我的验证消息“找到了电子邮件”。

What am I doing wrong? 我究竟做错了什么?

Update. 更新。

So, after the first answer I change code to: 因此,在第一个答案之后,我将代码更改为:

Template.Login.onRendered(() => {
  jQuery.validator.addMethod('checkEmailUnique', function(value, element) {
    return Meteor.wrapAsync(Meteor.call)('checkEmailUnique', value, element);
  });
});

In both cases I get validation message that email is not unique. 在这两种情况下,我都会收到验证消息,即电子邮件不是唯一的。

Your method is returning asynchronously so the return value is not getting passed back to the validator. 您的方法是异步返回的,因此返回值不会传递回验证器。 You need to wrap your Meteor.call() with Meteor.wrapAsync() in order to use it synchronously. 您需要将Meteor.call()Meteor.wrapAsync()包装Meteor.call()才能同步使用。

jQuery.validator.addMethod('checkEmailUnique', function(value, element) {
  return Meteor.wrapAsync(Meteor.call)('checkEmailUnique', value);
});

If you think your Meteor.call() might error then a try-catch block is necessary because Meteor.wrapAsync() is returning the result but not the error: 如果您认为您的Meteor.call()可能会出错,则必须尝试try-catch块,因为Meteor.wrapAsync()返回的是结果而不是错误:

jQuery.validator.addMethod('checkEmailUnique', function(value, element) {
  try {
    return Meteor.wrapAsync(Meteor.call)('checkEmailUnique', value);
  } catch(e) {
    console.log(e); // handle the error as required
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM