This repository has been archived by the owner on Feb 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
validatejs.js
1193 lines (1034 loc) · 34.8 KB
/
validatejs.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* validate.js 0.12.0
*
* (c) 2013-2017 Nicklas Ansman, 2013 Wrapp
* Validate.js may be freely distributed under the MIT license.
* For all details and documentation:
* http://validatejs.org/
*/
var _ = system.library.Underscore.require();
var instance = {};
(function(exports, module, define) {
"use strict";
// The main function that calls the validators specified by the constraints.
// The options are the following:
// - format (string) - An option that controls how the returned value is formatted
// * flat - Returns a flat array of just the error messages
// * grouped - Returns the messages grouped by attribute (default)
// * detailed - Returns an array of the raw validation data
// - fullMessages (boolean) - If `true` (default) the attribute name is prepended to the error.
//
// Please note that the options are also passed to each validator.
var validate = function(attributes, constraints, options) {
options = v.extend({}, v.options, options);
var results = v.runValidations(attributes, constraints, options)
, attr
, validator;
return validate.processValidationResults(results, options);
};
var v = validate;
// Copies over attributes from one or more sources to a single destination.
// Very much similar to underscore's extend.
// The first argument is the target object and the remaining arguments will be
// used as sources.
v.extend = function(obj) {
_.each([].slice.call(arguments, 1), function(source) {
for (var attr in source) {
obj[attr] = source[attr];
}
})
return obj;
};
v.extend(validate, {
// This is the version of the library as a semver.
// The toString function will allow it to be coerced into a string
version: {
major: 0,
minor: 12,
patch: 0,
metadata: null,
toString: function() {
var version = v.format("%{major}.%{minor}.%{patch}", v.version);
if (!v.isEmpty(v.version.metadata)) {
version += "+" + v.version.metadata;
}
return version;
}
},
// Below is the dependencies that are used in validate.js
// The constructor of the Promise implementation.
// If you are using Q.js, RSVP or any other A+ compatible implementation
// override this attribute to be the constructor of that promise.
// Since jQuery promises aren't A+ compatible they won't work.
Promise: typeof Promise !== "undefined" ? Promise : /* istanbul ignore next */ null,
EMPTY_STRING_REGEXP: /^\s*$/,
// Runs the validators specified by the constraints object.
// Will return an array of the format:
// [{attribute: "<attribute name>", error: "<validation result>"}, ...]
runValidations: function(attributes, constraints, options) {
var results = []
, attr
, validatorName
, value
, validators
, validator
, validatorOptions
, error;
if (v.isDomElement(attributes) || v.isJqueryElement(attributes)) {
attributes = v.collectFormValues(attributes);
}
// Loops through each constraints, finds the correct validator and run it.
for (attr in constraints) {
value = v.getDeepObjectValue(attributes, attr);
// This allows the constraints for an attribute to be a function.
// The function will be called with the value, attribute name, the complete dict of
// attributes as well as the options and constraints passed in.
// This is useful when you want to have different
// validations depending on the attribute value.
validators = v.result(constraints[attr], value, attributes, attr, options, constraints);
for (validatorName in validators) {
validator = v.validators[validatorName];
if (!validator) {
error = v.format("Unknown validator %{name}", {name: validatorName});
throw new Error(error);
}
validatorOptions = validators[validatorName];
// This allows the options to be a function. The function will be
// called with the value, attribute name, the complete dict of
// attributes as well as the options and constraints passed in.
// This is useful when you want to have different
// validations depending on the attribute value.
validatorOptions = v.result(validatorOptions, value, attributes, attr, options, constraints);
if (!validatorOptions) {
continue;
}
results.push({
attribute: attr,
value: value,
validator: validatorName,
globalOptions: options,
attributes: attributes,
options: validatorOptions,
error: validator.call(validator,
value,
validatorOptions,
attr,
attributes,
options)
});
}
}
return results;
},
// Takes the output from runValidations and converts it to the correct
// output format.
processValidationResults: function(errors, options) {
errors = v.pruneEmptyErrors(errors, options);
errors = v.expandMultipleErrors(errors, options);
errors = v.convertErrorMessages(errors, options);
var format = options.format || "grouped";
if (typeof v.formatters[format] === 'function') {
errors = v.formatters[format](errors);
} else {
throw new Error(v.format("Unknown format %{format}", options));
}
return v.isEmpty(errors) ? undefined : errors;
},
// Runs the validations with support for promises.
// This function will return a promise that is settled when all the
// validation promises have been completed.
// It can be called even if no validations returned a promise.
async: function(attributes, constraints, options) {
options = v.extend({}, v.async.options, options);
var WrapErrors = options.wrapErrors || function(errors) {
return errors;
};
// Removes unknown attributes
if (options.cleanAttributes !== false) {
attributes = v.cleanAttributes(attributes, constraints);
}
var results = v.runValidations(attributes, constraints, options);
return new v.Promise(function(resolve, reject) {
v.waitForResults(results).then(function() {
var errors = v.processValidationResults(results, options);
if (errors) {
reject(new WrapErrors(errors, options, attributes, constraints));
} else {
resolve(attributes);
}
}, function(err) {
reject(err);
});
});
},
single: function(value, constraints, options) {
options = v.extend({}, v.single.options, options, {
format: "flat",
fullMessages: false
});
return v({single: value}, {single: constraints}, options);
},
// Returns a promise that is resolved when all promises in the results array
// are settled. The promise returned from this function is always resolved,
// never rejected.
// This function modifies the input argument, it replaces the promises
// with the value returned from the promise.
waitForResults: function(results) {
// Create a sequence of all the results starting with a resolved promise.
return results.reduce(function(memo, result) {
// If this result isn't a promise skip it in the sequence.
if (!v.isPromise(result.error)) {
return memo;
}
return memo.then(function() {
return result.error.then(function(error) {
result.error = error || null;
});
});
}, new v.Promise(function(r) { r(); })); // A resolved promise
},
// If the given argument is a call: function the and: function return the value
// otherwise just return the value. Additional arguments will be passed as
// arguments to the function.
// Example:
// ```
// result('foo') // 'foo'
// result(Math.max, 1, 2) // 2
// ```
result: function(value) {
var args = [].slice.call(arguments, 1);
if (typeof value === 'function') {
value = value.apply(null, args);
}
return value;
},
// Checks if the value is a number. This function does not consider NaN a
// number like many other `isNumber` functions do.
isNumber: function(value) {
return typeof value === 'number' && !isNaN(value);
},
// Returns false if the object is not a function
isFunction: function(value) {
return typeof value === 'function';
},
// A simple check to verify that the value is an integer. Uses `isNumber`
// and a simple modulo check.
isInteger: function(value) {
return v.isNumber(value) && value % 1 === 0;
},
// Checks if the value is a boolean
isBoolean: function(value) {
return typeof value === 'boolean';
},
// Uses the `Object` function to check if the given argument is an object.
isObject: function(obj) {
return obj === Object(obj);
},
// Simply checks if the object is an instance of a date
isDate: function(obj) {
return obj instanceof Date;
},
// Returns false if the object is `null` of `undefined`
isDefined: function(obj) {
return obj !== null && obj !== undefined;
},
// Checks if the given argument is a promise. Anything with a `then`
// function is considered a promise.
isPromise: function(p) {
return !!p && v.isFunction(p.then);
},
isJqueryElement: function(o) {
return o && v.isString(o.jquery);
},
isDomElement: function(o) {
if (!o) {
return false;
}
if (!o.querySelectorAll || !o.querySelector) {
return false;
}
if (v.isObject(document) && o === document) {
return true;
}
// http://stackoverflow.com/a/384380/699304
/* istanbul ignore else */
if (typeof HTMLElement === "object") {
return o instanceof HTMLElement;
} else {
return o &&
typeof o === "object" &&
o !== null &&
o.nodeType === 1 &&
typeof o.nodeName === "string";
}
},
isEmpty: function(value) {
var attr;
// Null and undefined are empty
if (!v.isDefined(value)) {
return true;
}
// functions are non empty
if (v.isFunction(value)) {
return false;
}
// Whitespace only strings are empty
if (v.isString(value)) {
return v.EMPTY_STRING_REGEXP.test(value);
}
// For arrays we use the length property
if (v.isArray(value)) {
return value.length === 0;
}
// Dates have no attributes but aren't empty
if (v.isDate(value)) {
return false;
}
// If we find at least one property we consider it non empty
if (v.isObject(value)) {
for (attr in value) {
return false;
}
return true;
}
return false;
},
// Formats the specified strings with the given values like so:
// ```
// format("Foo: %{foo}", {foo: "bar"}) // "Foo bar"
// ```
// If you want to write %{...} without having it replaced simply
// prefix it with % like this `Foo: %%{foo}` and it will be returned
// as `"Foo: %{foo}"`
format: v.extend(function(str, vals) {
if (!v.isString(str)) {
return str;
}
return str.replace(v.format.FORMAT_REGEXP, function(m0, m1, m2) {
if (m1 === '%') {
return "%{" + m2 + "}";
} else {
return String(vals[m2]);
}
});
}, {
// Finds %{key} style patterns in the given string
FORMAT_REGEXP: /(%?)%\{([^\}]+)\}/g
}),
// "Prettifies" the given string.
// Prettifying means replacing [.\_-] with spaces as well as splitting
// camel case words.
prettify: function(str) {
if (v.isNumber(str)) {
// If there are more than 2 decimals round it to two
if ((str * 100) % 1 === 0) {
return "" + str;
} else {
return parseFloat(Math.round(str * 100) / 100).toFixed(2);
}
}
if (v.isArray(str)) {
return str.map(function(s) { return v.prettify(s); }).join(", ");
}
if (v.isObject(str)) {
return str.toString();
}
// Ensure the string is actually a string
str = "" + str;
return str
// Splits keys separated by periods
.replace(/([^\s])\.([^\s])/g, '$1 $2')
// Removes backslashes
.replace(/\\+/g, '')
// Replaces - and - with space
.replace(/[_-]/g, ' ')
// Splits camel cased words
.replace(/([a-z])([A-Z])/g, function(m0, m1, m2) {
return "" + m1 + " " + m2.toLowerCase();
})
.toLowerCase();
},
stringifyValue: function(value, options) {
var prettify = options && options.prettify || v.prettify;
return prettify(value);
},
isString: function(value) {
return typeof value === 'string';
},
isArray: function(value) {
return {}.toString.call(value) === '[object Array]';
},
// Checks if the object is a hash, which is equivalent to an object that
// is neither an array nor a function.
isHash: function(value) {
return v.isObject(value) && !v.isArray(value) && !v.isFunction(value);
},
contains: function(obj, value) {
if (!v.isDefined(obj)) {
return false;
}
if (v.isArray(obj)) {
return obj.indexOf(value) !== -1;
}
return value in obj;
},
unique: function(array) {
if (!v.isArray(array)) {
return array;
}
return array.filter(function(el, index, array) {
return array.indexOf(el) == index;
});
},
forEachKeyInKeypath: function(object, keypath, callback) {
if (!v.isString(keypath)) {
return undefined;
}
var key = ""
, i
, escape = false;
for (i = 0; i < keypath.length; ++i) {
switch (keypath[i]) {
case '.':
if (escape) {
escape = false;
key += '.';
} else {
object = callback(object, key, false);
key = "";
}
break;
case '\\':
if (escape) {
escape = false;
key += '\\';
} else {
escape = true;
}
break;
default:
escape = false;
key += keypath[i];
break;
}
}
return callback(object, key, true);
},
getDeepObjectValue: function(obj, keypath) {
if (!v.isObject(obj)) {
return undefined;
}
return v.forEachKeyInKeypath(obj, keypath, function(obj, key) {
if (v.isObject(obj)) {
return obj[key];
}
});
},
// This returns an object with all the values of the form.
// It uses the input name as key and the value as value
// So for example this:
// <input type="text" name="email" value="foo@bar.com"/>
// would return:
// {email: "foo@bar.com"}
collectFormValues: function(form, options) {
var values = {}
, i
, j
, input
, inputs
, option
, value;
if (v.isJqueryElement(form)) {
form = form[0];
}
if (!form) {
return values;
}
options = options || {};
inputs = form.querySelectorAll("input[name], textarea[name]");
for (i = 0; i < inputs.length; ++i) {
input = inputs.item(i);
if (v.isDefined(input.getAttribute("data-ignored"))) {
continue;
}
name = input.name.replace(/\./g, "\\\\.");
value = v.sanitizeFormValue(input.value, options);
if (input.type === "number") {
value = value ? +value : null;
} else if (input.type === "checkbox") {
if (input.attributes.value) {
if (!input.checked) {
value = values[name] || null;
}
} else {
value = input.checked;
}
} else if (input.type === "radio") {
if (!input.checked) {
value = values[name] || null;
}
}
values[name] = value;
}
inputs = form.querySelectorAll("select[name]");
for (i = 0; i < inputs.length; ++i) {
input = inputs.item(i);
if (v.isDefined(input.getAttribute("data-ignored"))) {
continue;
}
if (input.multiple) {
value = [];
for (j in input.options) {
option = input.options[j];
if (option && option.selected) {
value.push(v.sanitizeFormValue(option.value, options));
}
}
} else {
var _val = typeof input.options[input.selectedIndex] !== 'undefined' ? input.options[input.selectedIndex].value : '';
value = v.sanitizeFormValue(_val, options);
}
values[input.name] = value;
}
return values;
},
sanitizeFormValue: function(value, options) {
if (options.trim && v.isString(value)) {
value = value.trim();
}
if (options.nullify !== false && value === "") {
return null;
}
return value;
},
capitalize: function(str) {
if (!v.isString(str)) {
return str;
}
return str[0].toUpperCase() + str.slice(1);
},
// Remove all errors who's error attribute is empty (null or undefined)
pruneEmptyErrors: function(errors) {
return _.filter(errors, function(error){ return !v.isEmpty(error.error); });
},
// In
// [{error: ["err1", "err2"], ...}]
// Out
// [{error: "err1", ...}, {error: "err2", ...}]
//
// All attributes in an error with multiple messages are duplicated
// when expanding the errors.
expandMultipleErrors: function(errors) {
var ret = [];
_.each(errors, function(error) {
// Removes errors without a message
if (v.isArray(error.error)) {
_.each(error.error,function(msg) {
ret.push( v.extend({}, error, {error: msg}) );
});
} else {
ret.push(error);
}
});
return ret;
},
// Converts the error mesages by prepending the attribute name unless the
// message is prefixed by ^
convertErrorMessages: function(errors, options) {
options = options || {};
var ret = []
, prettify = options.prettify || v.prettify;
_.each(errors,function(errorInfo) {
var error = v.result(errorInfo.error,
errorInfo.value,
errorInfo.attribute,
errorInfo.options,
errorInfo.attributes,
errorInfo.globalOptions);
if (!v.isString(error)) {
ret.push(errorInfo);
return;
}
if (error[0] === '^') {
error = error.slice(1);
} else if (options.fullMessages !== false) {
error = v.capitalize(prettify(errorInfo.attribute)) + " " + error;
}
error = error.replace(/\\\^/g, "^");
error = v.format(error, {
value: v.stringifyValue(errorInfo.value, options)
});
ret.push(v.extend({}, errorInfo, {error: error}));
});
return ret;
},
// In:
// [{attribute: "<attributeName>", ...}]
// Out:
// {"<attributeName>": [{attribute: "<attributeName>", ...}]}
groupErrorsByAttribute: function(errors) {
var ret = {};
_.each(errors,function(error) {
var list = ret[error.attribute];
if (list) {
list.push(error);
} else {
ret[error.attribute] = [error];
}
});
return ret;
},
// In:
// [{error: "<message 1>", ...}, {error: "<message 2>", ...}]
// Out:
// ["<message 1>", "<message 2>"]
flattenErrorsToArray: function(errors) {
var errorMessages = _.map(errors, function(error) { return error.error; });
errorMessages = _.filter(errorMessages, function(value, index, self) {
return _.indexOf(self, value) === index;
});
return errorMessages;
},
cleanAttributes: function(attributes, whitelist) {
function whitelistCreator(obj, key, last) {
if (v.isObject(obj[key])) {
return obj[key];
}
return (obj[key] = last ? true : {});
}
function buildObjectWhitelist(whitelist) {
var ow = {}
, lastObject
, attr;
for (attr in whitelist) {
if (!whitelist[attr]) {
continue;
}
v.forEachKeyInKeypath(ow, attr, whitelistCreator);
}
return ow;
}
function cleanRecursive(attributes, whitelist) {
if (!v.isObject(attributes)) {
return attributes;
}
var ret = v.extend({}, attributes)
, w
, attribute;
for (attribute in attributes) {
w = whitelist[attribute];
if (v.isObject(w)) {
ret[attribute] = cleanRecursive(ret[attribute], w);
} else if (!w) {
delete ret[attribute];
}
}
return ret;
}
if (!v.isObject(whitelist) || !v.isObject(attributes)) {
return {};
}
whitelist = buildObjectWhitelist(whitelist);
return cleanRecursive(attributes, whitelist);
},
exposeModule: function(validate, root, exports, module, define) {
if (exports) {
if (module && module.exports) {
exports = module.exports = validate;
}
exports.validate = validate;
} else {
root.validate = validate;
if (validate.isFunction(define) && define.amd) {
define([], function () { return validate; });
}
}
},
warn: function(msg) {
if (typeof console !== "undefined" && console.warn) {
console.warn("[validate.js] " + msg);
}
},
error: function(msg) {
if (typeof console !== "undefined" && console.error) {
console.error("[validate.js] " + msg);
}
}
});
validate.validators = {
// Presence validates that the value isn't empty
presence: function(value, options) {
options = v.extend({}, this.options, options);
if (options.allowEmpty !== false ? !v.isDefined(value) : v.isEmpty(value)) {
return options.message || this.message || "can't be blank";
}
},
length: function(value, options, attribute) {
// Empty values are allowed
if (!v.isDefined(value)) {
return;
}
options = v.extend({}, this.options, options);
var is = options.is
, maximum = options.maximum
, minimum = options.minimum
, tokenizer = options.tokenizer || function(val) { return val; }
, err
, errors = [];
value = tokenizer(value);
var length = value.length;
if(!v.isNumber(length)) {
v.error(v.format("Attribute %{attr} has a non numeric value for `length`", {attr: attribute}));
return options.message || this.notValid || "has an incorrect length";
}
// Is checks
if (v.isNumber(is) && length !== is) {
err = options.wrongLength ||
this.wrongLength ||
"is the wrong length (should be %{count} characters)";
errors.push(v.format(err, {count: is}));
}
if (v.isNumber(minimum) && length < minimum) {
err = options.tooShort ||
this.tooShort ||
"is too short (minimum is %{count} characters)";
errors.push(v.format(err, {count: minimum}));
}
if (v.isNumber(maximum) && length > maximum) {
err = options.tooLong ||
this.tooLong ||
"is too long (maximum is %{count} characters)";
errors.push(v.format(err, {count: maximum}));
}
if (errors.length > 0) {
return options.message || errors;
}
},
numericality: function(value, options, attribute, attributes, globalOptions) {
// Empty values are fine
if (!v.isDefined(value)) {
return;
}
options = v.extend({}, this.options, options);
var errors = []
, name
, count
, checks = {
greaterThan: function(v, c) { return v > c; },
greaterThanOrEqualTo: function(v, c) { return v >= c; },
equalTo: function(v, c) { return v === c; },
lessThan: function(v, c) { return v < c; },
lessThanOrEqualTo: function(v, c) { return v <= c; },
divisibleBy: function(v, c) { return v % c === 0; }
}
, prettify = options.prettify ||
(globalOptions && globalOptions.prettify) ||
v.prettify;
// Strict will check that it is a valid looking number
if (v.isString(value) && options.strict) {
var pattern = "^-?(0|[1-9]\\d*)";
if (!options.onlyInteger) {
pattern += "(\\.\\d+)?";
}
pattern += "$";
if (!(new RegExp(pattern).test(value))) {
return options.message ||
options.notValid ||
this.notValid ||
this.message ||
"must be a valid number";
}
}
// Coerce the value to a number unless we're being strict.
if (options.noStrings !== true && v.isString(value) && !v.isEmpty(value)) {
value = +value;
}
// If it's not a number we shouldn't continue since it will compare it.
if (!v.isNumber(value)) {
return options.message ||
options.notValid ||
this.notValid ||
this.message ||
"is not a number";
}
// Same logic as above, sort of. Don't bother with comparisons if this
// doesn't pass.
if (options.onlyInteger && !v.isInteger(value)) {
return options.message ||
options.notInteger ||
this.notInteger ||
this.message ||
"must be an integer";
}
for (name in checks) {
count = options[name];
if (v.isNumber(count) && !checks[name](value, count)) {
// This picks the default message if specified
// For example the greaterThan check uses the message from
// this.notGreaterThan so we capitalize the name and prepend "not"
var key = "not" + v.capitalize(name);
var msg = options[key] ||
this[key] ||
this.message ||
"must be %{type} %{count}";
errors.push(v.format(msg, {
count: count,
type: prettify(name)
}));
}
}
if (options.odd && value % 2 !== 1) {
errors.push(options.notOdd ||
this.notOdd ||
this.message ||
"must be odd");
}
if (options.even && value % 2 !== 0) {
errors.push(options.notEven ||
this.notEven ||
this.message ||
"must be even");
}
if (errors.length) {
return options.message || errors;
}
},
datetime: v.extend(function(value, options) {
if (!v.isFunction(this.parse) || !v.isFunction(this.format)) {
throw new Error("Both the parse and format functions needs to be set to use the datetime/date validator");
}
// Empty values are fine
if (!v.isDefined(value)) {
return;
}
options = v.extend({}, this.options, options);
var err
, errors = []
, earliest = options.earliest ? this.parse(options.earliest, options) : NaN
, latest = options.latest ? this.parse(options.latest, options) : NaN;
value = this.parse(value, options);
// 86400000 is the number of milliseconds in a day, this is used to remove
// the time from the date
if (isNaN(value) || options.dateOnly && value % 86400000 !== 0) {
err = options.notValid ||
options.message ||
this.notValid ||
"must be a valid date";
return v.format(err, {value: arguments[0]});
}
if (!isNaN(earliest) && value < earliest) {
err = options.tooEarly ||
options.message ||
this.tooEarly ||
"must be no earlier than %{date}";
err = v.format(err, {
value: this.format(value, options),
date: this.format(earliest, options)
});
errors.push(err);
}
if (!isNaN(latest) && value > latest) {
err = options.tooLate ||
options.message ||
this.tooLate ||
"must be no later than %{date}";
err = v.format(err, {
date: this.format(latest, options),
value: this.format(value, options)
});
errors.push(err);
}
if (errors.length) {
return v.unique(errors);
}
}, {
parse: null,
format: null
}),
date: function(value, options) {
options = v.extend({}, options, {dateOnly: true});
return v.validators.datetime.call(v.validators.datetime, value, options);
},
format: function(value, options) {
if (v.isString(options) || (options instanceof RegExp)) {
options = {pattern: options};
}
options = v.extend({}, this.options, options);
var message = options.message || this.message || "is invalid"
, pattern = options.pattern
, match;
// Empty values are allowed
if (!v.isDefined(value)) {