简体   繁体   中英

Client and server side validation in Meteor JS

So I'm using Meteor's 'methods' to transmit data between the client and server. Is there a recommended pattern for validating data? I've seen SimpleSchema used on the server like this a bit

Lists.schema = new SimpleSchema({
  name: {type: String},
  incompleteCount: {type: Number, defaultValue: 0},
  userId: {type: String, regEx: SimpleSchema.RegEx.Id, optional: true}
});

...

const list = {
  name: 'My list',
  incompleteCount: 3
};
Lists.schema.validate(list);

...which makes sense, is there something I similar I should be using on the client to validate forms? Any extra information would be appreciated as well.

You can use simple-schema to validate arguments in methods when you use Meteor's validated method package.

https://github.com/meteor/validated-method

One advantage to this is that you can validate the args on the client in the method simulation so if there is an error, the method is rejected before it even gets to the server.

You can also use the Meteor's check package ( https://docs.meteor.com/api/check.html ) as part of your validation.

In terms of validating forms, there are many solutions. An example would be jQuery validation

Client side validation requirement arises when you are not using autoforms. If wrong values are passed from UI then Simpleschema generates error on server side.

If you desire to keep no validations on client side without using autoform, then you can use check functionality to check data sent from UI. When any check fails, catch in asynchronous . Meteor.call and using bootstrap and jquery you can show user friendly message on UI.

Or else use normal JavaScript and gquery to.meet your needs. This procedure is very tedious to maintain later when the application is live on the server. Just to change simple validation or condition entire code will have to built and minified to suit server production ready code. But in case if you use simpleschema and autoforms, you will have to change app.js file and restart the application (may be using pm2 as I do) and your application will work fine.

I would like also to add that communication between server and client in Meteor are done through "publications" (serverside) and "subscriptions" (client side) to certain publications.

To my understanding, methods in Meteor are only for CRUD operations for example and they can be called remotely from the client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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