Validation
The schema's modifiers are rules, and the store enforces them whenever a record is written. createRecord() checks every field; update() checks the fields it changes. When a rule fails, nothing is written and a PuzzleValidationError is thrown.
The error carries the details. error.message is the first problem, and error.errors lists them all as { field, rule, message }, in schema order. Every rule takes its own message as the last argument: .required('Every album needs a title'), .min(10, 'Too cheap'). Leave it out and the message names the field and the rule.
To check data without throwing, ask the model. Album.validate(data) returns { valid, errors }, and record.validate() checks a record you hold, which suits a form that shows its problems before it saves.
Your turn
- In
album.js, give the title rule a message:.required('Every album needs a title'). - In
app.js, add abeforeMount(app)hook to the config and try to create an album with no title. Catch the error, and log it only if it is aPuzzleValidationError(import it from@magic-spells/puzzle):
beforeMount(app) {
try {
app.store.createRecord('album', { id: 'a9', artist: 'Nobody Yet', price: 20 });
} catch (error) {
if (!(error instanceof PuzzleValidationError)) throw error;
console.warn(error.message);
console.log(error.errors);
}
},
- Read the console under the preview. The shop still shows eight albums: the bad one never got in.
That is the datastore. Chapter 5 goes deep on what a view's template can say.