fuzzybabybunny
fuzzybabybunny

Reputation: 5254

Changing Meteor schema validations at different stages of object lifecycle?

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.

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?

Upvotes: 0

Views: 95

Answers (1)

CodeChimp
CodeChimp

Reputation: 8154

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.

Upvotes: 2

Related Questions