UNPKG

813 BJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6const Base = require('./Validator');
7
8module.exports = class JsonValidator extends Base {
9
10 constructor (config) {
11 super({
12 parsed: false,
13 ...config
14 });
15 }
16
17 getMessage () {
18 return this.createMessage(this.message, 'Invalid JSON');
19 }
20
21 async validateAttr (attr, model) {
22 let value = model.get(attr);
23 if (typeof value === 'string') {
24 try {
25 value = JSON.parse(value);
26 if (this.parsed) {
27 model.set(attr, value);
28 }
29 } catch {
30 this.addError(model, attr, this.getMessage());
31 }
32 }
33 }
34};
\No newline at end of file