-
Notifications
You must be signed in to change notification settings - Fork 1
/
messages.js
96 lines (76 loc) · 2.64 KB
/
messages.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
var Attributes = require('./attributes');
var Messages = function(lang, messages) {
this.lang = lang;
this.messages = messages;
this.customMessages = {};
this.attributeNames = {};
};
Messages.prototype = {
constructor: Messages,
_setCustom: function(customMessages) {
this.customMessages = customMessages || {};
},
_setAttributeNames: function(attributes) {
this.attributeNames = attributes;
},
_setAttributeFormatter: function(func) {
this.attributeFormatter = func;
},
_getAttributeName: function(attribute) {
var name = attribute;
if (this.attributeNames.hasOwnProperty(attribute)) {
return this.attributeNames[attribute];
} else if (this.messages.attributes.hasOwnProperty(attribute)) {
name = this.messages.attributes[attribute];
}
if (this.attributeFormatter) {
name = this.attributeFormatter(name);
}
return name;
},
all: function() {
return this.messages;
},
render: function(rule) {
if (rule.customMessage) {
return rule.customMessage;
}
var template = this._getTemplate(rule);
if (Attributes.replacements[rule.name]) {
return Attributes.replacements[rule.name].apply(this, [template, rule]);
} else {
return this._replacePlaceholders(rule, template, {});
}
},
_getTemplate: function(rule) {
var messages = this.messages;
var template = messages.def;
var customMessages = this.customMessages;
var formats = [rule.name + '.' + rule.attribute, rule.name];
for (var i = 0, format; i < formats.length; i++) {
format = formats[i];
if (customMessages.hasOwnProperty(format)) {
template = customMessages[format];
break;
} else if (messages.hasOwnProperty(format)) {
template = messages[format];
break;
}
}
if (typeof template === 'object') {
template = template[rule._getValueType()];
}
return template;
},
_replacePlaceholders: function(rule, template, data) {
data.attribute = this._getAttributeName(rule.attribute);
data[rule.name] = data[rule.name] || rule.getParameters().join(',');
if (typeof template === 'string' && typeof data === 'object') {
for (attribute in data) {
template = template.replace(new RegExp(':' + attribute, 'g'), data[attribute]);
}
}
return template;
}
};
module.exports = Messages;