Sergei R
Sergei R

Reputation: 721

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.

Upvotes: 0

Views: 774

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20226

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.

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:

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
  }
});

Upvotes: 1

Related Questions