Changing Meteor schema validations at different stages of object lifecycle?

筅森魡賤 提交于 2019-12-12 01:13:24

问题


I'm making a complex form for a shopping cart and I want to validate different parts of my order object at different stages of the order process.

OrderSchema = new SimpleSchema({
  itemsOrdered: {
    type: [Object],
    optional: false,
  },
  totalPrice: {
    type: Number,
    optional: false,
  },
  status: {
    type: String,
    optional: false
  },
  termsAgreed: {
    type: Boolean,
    optional: false
  },
  customerAddress: {
    type: Object,
    optional: false
  },
  stripePaymentInfo: {
    type: Object,
    optional: true,
    blackbox: true
  },
});

It's kind of a mess IMO because the different fields need to be validated differently at different stages of the order's life cycle.

  • a user still in the middle of selecting products doesn't yet have termsAgreed, customerAddress, or stripePaymentInfo but I don't want validation to fail because of these two since it's still too early in the ordering process to be validating this

  • a user filling out their customer address doesn't need stripePaymentInfo yet or termsAgreed.

  • etc

I need the schema to validate successfully at different stages to trigger things like enabling continue buttons.

The problem is that autoform always wants to use the entire schema to validate the entire object, which is fine for simple objects like Contact Me forms and such that don't have much of a lifecycle.

Is there a best practice or pattern for complex object validation at different stages of their life cycles?


回答1:


I think the cleanest would be to have one schema with custom validation that validates based on the "state" of the thing in questions, in this case the Order. The "state" could be determined on something that's pre-existing, if you can identify something there already, or by some "state value" you place in your Order, like an enumeration or something. This way your validation is using out-of-the-box SimpleSchema functionality, and you are not tied to any one-off solution that might break functionality downstream.

You would then write a custom validation function that would look at the state and either do the validation if the state calls for it, or simply returns that the validation is good to let it pass through correctly without validation errors.



来源:https://stackoverflow.com/questions/38558313/changing-meteor-schema-validations-at-different-stages-of-object-lifecycle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!