1 | var Errors = function() {
|
2 | this.errors = {};
|
3 | };
|
4 |
|
5 | Errors.prototype = {
|
6 | constructor: Errors,
|
7 |
|
8 | /**
|
9 | * Add new error message for given attribute
|
10 | *
|
11 | * @param {string} attribute
|
12 | * @param {string} message
|
13 | * @return {void}
|
14 | */
|
15 | add: function(attribute, message) {
|
16 | if (!this.has(attribute)) {
|
17 | this.errors[attribute] = [];
|
18 | }
|
19 |
|
20 | if (this.errors[attribute].indexOf(message) === -1) {
|
21 | this.errors[attribute].push(message);
|
22 | }
|
23 | },
|
24 |
|
25 | /**
|
26 | * Returns an array of error messages for an attribute, or an empty array
|
27 | *
|
28 | * @param {string} attribute A key in the data object being validated
|
29 | * @return {array} An array of error messages
|
30 | */
|
31 | get: function(attribute) {
|
32 | if (this.has(attribute)) {
|
33 | return this.errors[attribute];
|
34 | }
|
35 |
|
36 | return [];
|
37 | },
|
38 |
|
39 | /**
|
40 | * Returns the first error message for an attribute, false otherwise
|
41 | *
|
42 | * @param {string} attribute A key in the data object being validated
|
43 | * @return {string|false} First error message or false
|
44 | */
|
45 | first: function(attribute) {
|
46 | if (this.has(attribute)) {
|
47 | return this.errors[attribute][0];
|
48 | }
|
49 |
|
50 | return false;
|
51 | },
|
52 |
|
53 | /**
|
54 | * Get all error messages from all failing attributes
|
55 | *
|
56 | * @return {Object} Failed attribute names for keys and an array of messages for values
|
57 | */
|
58 | all: function() {
|
59 | return this.errors;
|
60 | },
|
61 |
|
62 | /**
|
63 | * Determine if there are any error messages for an attribute
|
64 | *
|
65 | * @param {string} attribute A key in the data object being validated
|
66 | * @return {boolean}
|
67 | */
|
68 | has: function(attribute) {
|
69 | if (this.errors.hasOwnProperty(attribute)) {
|
70 | return true;
|
71 | }
|
72 |
|
73 | return false;
|
74 | }
|
75 | };
|
76 |
|
77 | module.exports = Errors;
|