themeteorchef / base

A starting point for Meteor apps.
http://themeteorchef.com/base
MIT License
695 stars 253 forks source link

Could you example custom "jquery validate" with "Meteor Method"? #228

Closed thearabbit closed 7 years ago

thearabbit commented 7 years ago

Could you example custom "jquery validate" with "Meteor Method"? Example: unique name,...

themeteorchef commented 7 years ago

I'm not sure I understand, can you give me more details? jQuery Validate is meant only for client-side validation.

Here's an example from Base on how to define that: https://github.com/themeteorchef/base/blob/master/imports/modules/login.js#L31

thearabbit commented 7 years ago

Example I would like to create staff form

// Fields
name // unique
gender
dateOfBirth
address

And then set name field with unique, so I need to create custom validate on jquery validate that check the value on Meteor.methods({......}).

thearabbit commented 7 years ago

Like the simple schema

username: {
  type: String,
  custom: function () {
    if (Meteor.isClient && this.isSet) {
      Meteor.call("accountsIsUsernameAvailable", this.value, function (error, result) {
        if (!result) {
          Meteor.users.simpleSchema().namedContext("createUserForm").addInvalidKeys([{name: "username", type: "notUnique"}]);
        }
      });
    }
  }
}
themeteorchef commented 7 years ago

@thearabbit take a peek at this https://themeteorchef.com/tutorials/validating-forms-with-jquery-validation

thearabbit commented 7 years ago

Look great tutorials. but I would like to use custom validate with Meteor Method on Server.

$.validator.addMethod( 'bookUnique', ( title ) => {
   Meteor.call('bookUnique', title,(error, result){
      return result; // Can't return, and waiting
   });
});

// Method
Meteor.methods({
   bookUnique(title){
      let exists = Books.findOne( { "title": title }, { fields: { "title": 1 } } );
      return exists ? false : true;
   }
});

Please help me, bc I can not return Meteor.call().

themeteorchef commented 7 years ago

You'll need to use a session variable or Reactive Var to get the response out of the Meteor.call block. Something like this...

Session.setDefault('isBookUniqueValidation', true);

$.validator.addMethod( 'bookUnique', ( title ) => {
   Meteor.call('bookUnique', title,(error, result){
      Session.set('isBookUniqueValidation', result);
   });
   return Session.get('isBookUniqueValidation');
});
thearabbit commented 7 years ago

I tried this too, but if my method do for a long time so it don't wait the method. (it mean that the submit is success without check custom validate method)

themeteorchef commented 7 years ago

In that case you'll want it to be false by default instead of true so that the validation blocks indefinitely. Not much you can do there if your method is slow to respond.

thearabbit commented 7 years ago

Thanks I understand.