forked from whatgoodisaroad/validity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validity.js
1322 lines (1081 loc) · 43.8 KB
/
validity.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
/*
* jQuery.validity v1.3.1
* http://validity.thatscaptaintoyou.com/
* https://github.com/whatgoodisaroad/validity
*
* Dual licensed under MIT and GPL
*
* Date: 2013-02-10 (Sunday, 10 February 2013)
*/
(function($, undefined) {
// Default settings:
///////////////////////////////////////////////////////////////////////////////
var
defaults = {
// The default output mode is tooltip because it requires no
// dependencies:
outputMode:"tooltip",
// The this property is set to true, validity will scroll the browser
// viewport so that the first error is visible when validation fails:
scrollTo:false,
// If this setting is true, modal errors will disappear when they are
// clicked on:
modalErrorsClickable:true,
// If a field name cannot be otherwise inferred, this will be used:
defaultFieldName:"This field",
// jQuery selector to filter down to validation-supported elements:
elementSupport:":text, :password, textarea, select, :radio, :checkbox, input[type='hidden'], input[type='tel'], input[type='email']",
// Function to stringify argments for use when generating error
// messages. Primarily, it just generates pretty date strings:
argToString:function(val) {
return val.getDate ? [
val.getMonth() + 1,
val.getDate(),
val.getFullYear()
].join("/") :
val + "";
},
debugPrivates:false
},
__private;
// Static functions and properties:
///////////////////////////////////////////////////////////////////////////////
$.validity = {
// Clone the defaults. They can be overridden with the setup function:
settings:$.extend(defaults, {}),
// Built-in library of format-checking tools for use with the match
// validator as well as the nonHtml validator:
patterns:{
integer:/^\d+$/,
// Used to use Date.parse(), which was the cause of Issue 9, where the
// function would accept 09/80/2009 as parseable. The fix is to use a
// RegExp that will only accept American Middle-Endian form. See the
// Internationalization section in the documentation for how to cause
// it to support other date formats:
date:/^((0?\d)|(1[012]))[\/-]([012]?\d|30|31)[\/-]\d{1,4}$/,
email:/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,
usd:/^\$?((\d{1,3}(,\d{3})*)|\d+)(\.(\d{2})?)?$/,
url:/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,
// Number should accept floats or integers, be they positive or
// negative. It should also support scientific-notation, written as a
// lower or capital 'E' followed by the radix. Number assumes base 10.
// Unlike the native parseFloat or parseInt functions, this should not
// accept trailing Latin characters.
number:/^[+-]?(\d+(\.\d*)?|\.\d+)([Ee]-?\d+)?$/,
zip:/^\d{5}(-\d{4})?$/,
phone:/^[2-9]\d{2}-\d{3}-\d{4}$/,
guid:/^(\{?([0-9a-fA-F]){8}-(([0-9a-fA-F]){4}-){3}([0-9a-fA-F]){12}\}?)$/,
time12:/^((0?\d)|(1[012])):[0-5]\d?\s?[aApP]\.?[mM]\.?$/,
time24:/^(20|21|22|23|[01]\d|\d)(([:][0-5]\d){1,2})$/,
nonHtml:/^[^<>]*$/
},
// Built-in set of default error messages (for use when a message isn't
// specified):
messages:{
require:"#{field} is required.",
// Format validators:
match:"#{field} is in an invalid format.",
integer:"#{field} must be a positive, whole number.",
date:"#{field} must be formatted as a date. (mm/dd/yyyy)",
email:"#{field} must be formatted as an email.",
usd:"#{field} must be formatted as a US Dollar amount.",
url:"#{field} must be formatted as a URL.",
number:"#{field} must be formatted as a number.",
zip:"#{field} must be formatted as a zipcode ##### or #####-####.",
phone:"#{field} must be formatted as a phone number ###-###-####.",
guid:"#{field} must be formatted as a guid like {3F2504E0-4F89-11D3-9A0C-0305E82C3301}.",
time24:"#{field} must be formatted as a 24 hour time: 23:00.",
time12:"#{field} must be formatted as a 12 hour time: 12:00 AM/PM",
// Value range messages:
lessThan:"#{field} must be less than #{max}.",
lessThanOrEqualTo:"#{field} must be less than or equal to #{max}.",
greaterThan:"#{field} must be greater than #{min}.",
greaterThanOrEqualTo:"#{field} must be greater than or equal to #{min}.",
range:"#{field} must be between #{min} and #{max}.",
// Value length messages:
tooLong:"#{field} cannot be longer than #{max} characters.",
tooShort:"#{field} cannot be shorter than #{min} characters.",
// Composition validators:
nonHtml:"#{field} cannot contain HTML characters.",
alphabet:"#{field} contains disallowed characters.",
minCharClass:"#{field} cannot have more than #{min} #{charClass} characters.",
maxCharClass:"#{field} cannot have less than #{min} #{charClass} characters.",
// Aggregate validator messages:
equal:"Values don't match.",
distinct:"A value was repeated.",
sum:"Values don't add to #{sum}.",
sumMax:"The sum of the values must be less than #{max}.",
sumMin:"The sum of the values must be greater than #{min}.",
// Radio validator messages:
radioChecked:"The selected value is not valid.",
generic:"Invalid."
},
// Abstract output:
out:{
start:function() {
this.defer("start");
},
end:function(results) {
this.defer("end", results);
},
raise:function($obj, msg) {
this.defer("raise", $obj, msg);
},
raiseAggregate:function($obj, msg) {
this.defer("raiseAggregate", $obj, msg);
},
defer:function(name) {
var
v = $.validity,
o = v.outputs[v.settings.outputMode];
o[name].apply(
o,
Array.prototype.slice.call(arguments, 1)
);
}
},
// Character classes can be used to determine the quantity of a given type
// of character in a string:
charClasses:{
alphabetical:/\w/g,
numeric:/\d/g,
alphanumeric:/[A-Za-z0-9]/g,
symbol:/[^A-Za-z0-9]/g
},
// Object to contain the output modes. The three built-in output modes are
// installed later on in this script.
outputs:{},
// By default, private members are not exposed.
__private:undefined,
// Override the default settings with user-specified ones.
setup:function(options) {
this.settings = $.extend(this.settings, options);
if (this.settings.debugPrivates) {
this.__private = __private;
}
else {
this.__private = undefined;
}
},
// Object to store information about ongoing validation. When validation
// starts, this will be set to a report object. When validators fail, they
// will inform this object. When validation is completed, this object will
// contain the information of whether it succeeded:
report:null,
// Determine whether validity is in the middle of validation:
isValidating:function() {
return !!this.report;
},
// Function to prepare validity to start validating:
start:function() {
// The output mode should be notified that validation is starting. This
// usually means that the output mode will erase errors from the
// document in whatever way the mode needs to:
this.out.start();
// Initialize the report object:
this.report = { errors:0, valid:true };
},
// Function called when validation is over to examine the results and
// clean-up:
end:function() {
// Null coalescence: fix for Issue 5:
var results = this.report || { errors: 0, valid: true };
this.report = null;
// Notify the current output mode that validation is over:
this.out.end(results);
return results;
},
// Remove validiation errors:
clear:function() {
this.start();
this.end();
}
};
// jQuery instance methods:
///////////////////////////////////////////////////////////////////////////////
$.fn.extend({
// The validity function is how validation can be bound to forms. The user
// may pass in a validation function or, as a shortcut, pass in a string of
// a CSS selector that grabs all the inputs to require:
validity:function(arg) {
return this.each(
function() {
// Only operate on forms:
if (this.tagName.toLowerCase() == "form") {
var f = null;
// If the user entered a string to select the inputs to
// require, then make the validation logic ad hoc:
if (typeof (arg) == "string") {
f = function() {
$(arg).require();
};
}
// If the user entered a validation function then just call
// that at the appropriate time:
else if ($.isFunction(arg)) {
f = arg;
}
if (arg) {
$(this).bind(
"submit",
function() {
$.validity.start();
f();
return $.validity.end().valid;
}
);
}
}
}
);
},
// Validators:
///////////////////////////////////////////////////////////////////////////
// Common validators:
///////////////////////////////////////////////////////////////////////////
// Validate whether the field has a value.
require:function(msg) {
return validate(
this,
function(obj) {
return !!$(obj).val().length;
},
msg || $.validity.messages.require
);
},
// Validate whether the field matches a regex.
match:function(rule, msg) {
// If a default message is to be used:
if (!msg) {
// First grab the generic one:
msg = $.validity.messages.match;
// If there's a more specific one, use that.
if (typeof (rule) === "string" && $.validity.messages[rule]) {
msg = $.validity.messages[rule];
}
}
// If the rule is named, rather than specified:
if (typeof (rule) == "string") {
rule = $.validity.patterns[rule];
}
return validate(
this,
// Some of the named rules can be functions, such as 'date'. If the
// discovered rule is a function use it as such. Otherwise, assume
// it's a RegExp.
$.isFunction(rule) ?
function(obj) {
return !obj.value.length || rule(obj.value);
} :
function(obj) {
// Fix for regexes where the global flag is set. Make sure
// to test from the start of the string.
if (rule.global) {
rule.lastIndex = 0;
}
return !obj.value.length || rule.test(obj.value);
},
msg
);
},
range:function(min, max, msg) {
return validate(
this,
min.getTime && max.getTime ?
// If both arguments are dates then use them that way.
function(obj) {
var d = new Date(obj.value);
return d >= new Date(min) && d <= new Date(max);
} :
min.substring && max.substring && Big ?
// If both arguments are strings then parse them using the
// Arbitrary-Precision library.
function(obj) {
var n = new Big(obj.value);
return (
n.greaterThanOrEqualTo(new Big(min)) &&
n.lessThanOrEqualTo(new Big(max))
);
} :
// Otherwise treat them like floats.
function(obj) {
var f = parseFloat(obj.value);
return f >= min && f <= max;
},
msg || format(
$.validity.messages.range, {
min:$.validity.settings.argToString(min),
max:$.validity.settings.argToString(max)
}
)
);
},
greaterThan:function(min, msg) {
return validate(
this,
min.getTime ?
function(obj) {
return new Date(obj.value) > min;
} :
min.substring && Big ?
function(obj) {
return new Big(obj.value).greaterThan(new Big(min));
} :
function(obj) {
return parseFloat(obj.value) > min;
},
msg || format(
$.validity.messages.greaterThan, {
min:$.validity.settings.argToString(min)
}
)
);
},
greaterThanOrEqualTo:function(min, msg) {
return validate(
this,
min.getTime ?
function(obj) {
return new Date(obj.value) >= min;
} :
min.substring && Big ?
function(obj) {
return new Big(obj.value).greaterThanOrEqualTo(new Big(min));
} :
function(obj) {
return parseFloat(obj.value) >= min;
},
msg || format(
$.validity.messages.greaterThanOrEqualTo, {
min:$.validity.settings.argToString(min)
}
)
);
},
lessThan:function(max, msg) {
return validate(
this,
max.getTime ?
function(obj) {
return new Date(obj.value) < max;
} :
max.substring && Big ?
function(obj) {
return new Big(obj.value).lessThan(new Big(max));
} :
function(obj) {
return parseFloat(obj.value) < max;
},
msg || format(
$.validity.messages.lessThan, {
max:$.validity.settings.argToString(max)
}
)
);
},
lessThanOrEqualTo:function(max, msg) {
return validate(
this,
max.getTime ?
function(obj) {
return new Date(obj.value) <= max;
} :
max.substring && Big ?
function(obj) {
return new Big(obj.value).lessThanOrEqualTo(new Big(max));
} :
function(obj) {
return parseFloat(obj.value) <= max;
},
msg || format(
$.validity.messages.lessThanOrEqualTo, {
max:$.validity.settings.argToString(max)
}
)
);
},
maxLength:function(max, msg) {
return validate(
this,
function(obj) {
return obj.value.length <= max;
},
msg || format(
$.validity.messages.tooLong, {
max:max
}
)
);
},
minLength:function(min, msg) {
return validate(
this,
function(obj) {
return obj.value.length >= min;
},
msg || format(
$.validity.messages.tooShort, {
min:min
}
)
);
},
alphabet:function(alpha, msg) {
var chars = [];
return validate(
this,
function(obj) {
// For each character in the string, ensure that it's in the
// alphabet definition:
for (var idx = 0; idx < obj.value.length; ++idx) {
if (alpha.indexOf(obj.value.charAt(idx)) == -1) {
chars.push(obj.value.charAt(idx));
return false;
}
}
return true;
},
msg || format(
$.validity.messages.alphabet, {
chars:chars.join(", ")
}
)
);
},
minCharClass:function(charClass, min, msg) {
if (typeof(charClass) == "string") {
charClass = charClass.toLowerCase();
if ($.validity.charClasses[charClass]) {
charClass = $.validity.charClasses[charClass];
}
}
return validate(
this,
function(obj) {
return (obj.value.match(charClass) || []).length >= min;
},
msg || format(
$.validity.messages.minCharClass, {
min:min,
charClass:charClass
}
)
);
},
maxCharClass:function(charClass, max, msg) {
if (typeof(charClass) == "string") {
charClass = charClass.toLowerCase();
if ($.validity.charClasses[charClass]) {
charClass = $.validity.charClasses[charClass];
}
}
return validate(
this,
function(obj) {
return (obj.value.match(charClass) || []).length <= max;
},
msg || format(
$.validity.messages.maxCharClass, {
max:max,
charClass:charClass
}
)
);
},
// Validate that the input does not contain potentially dangerous strings.
nonHtml:function(msg) {
return validate(
this,
function(obj) {
return $.validity.patterns.nonHtml.test(obj.value);
},
msg || $.validity.messages.nonHtml
);
},
// Aggregate validators:
///////////////////////////////////////////////////////////////////////////
// Validate that all matched elements bear the same values. Accepts a
// function to transform the values for testing.
equal:function(arg0, arg1) {
var
// If a reduced set is attached, use it. Also, remove unsupported
// elements.
$reduction = (this.reduction || this)
.filter($.validity.settings.elementSupport),
transform = function(val) {
return val;
},
msg = $.validity.messages.equal;
if ($reduction.length) {
// Figure out what arguments were specified.
if ($.isFunction(arg0)) {
transform = arg0;
if (typeof (arg1) == "string") {
msg = arg1;
}
}
else if (typeof (arg0) == "string") {
msg = arg0;
}
var
map = $.map(
$reduction,
function(obj) {
return transform(obj.value);
}
),
// Get the first value.
first = map[0],
valid = true;
// If any value is not equal to the first value, then they aren't
// all equal, and it's not valid.
for (var i in map) {
if (map[i] != first) {
valid = false;
}
}
if (!valid) {
raiseAggregateError($reduction, msg);
// The set reduces to zero valid elements.
this.reduction = $([]);
}
}
return this;
},
// Validate that all matched elements bear distinct values. Accepts an
// optional function to transform the values for testing.
distinct:function(arg0, arg1) {
var
// If a reduced set is attached, use it.
// Also, remove unsupported elements.
$reduction = (this.reduction || this).filter($.validity.settings.elementSupport),
transform = function(val) {
return val;
},
msg = $.validity.messages.distinct,
// An empty array to store already-examined values
subMap = [],
// An array with repeated values
repeatedVal = [],
valid = true;
if ($reduction.length) {
// Figure out what arguments were specified.
if ($.isFunction(arg0)) {
transform = arg0;
if (typeof (arg1) == "string") {
msg = arg1;
}
}
else if (typeof (arg0) == "string") {
msg = arg0;
}
// Map all the matched values into an array.
var map = $.map(
$reduction,
function(obj) {
return transform(obj.value);
}
);
// For each transformed value:
for (var i1 = 0; i1 < map.length; ++i1) {
// Unless it's an empty string:
if (map[i1].length) {
// For each value we've already looked at:
for (var i2 = 0; i2 < subMap.length; ++i2) {
// If we've already seen the transformed value:
if (subMap[i2] == map[i1]) {
valid = false;
// Collect repeated values
repeatedVal.push(map[i1]);
}
}
// We looked at the value.
subMap.push(map[i1]);
}
}
if (!valid) {
// Remove duplicates of duplicates
repeatedVal = $.unique(repeatedVal);
// For all repeated values found...
for (
var
i = 0,
repeatedLength = repeatedVal.length;
i < repeatedLength;
++i) {
// raise the error - aggregate will use last repeated value
raiseAggregateError(
$reduction.filter(
"[value=\'" + repeatedVal[i] + "\']"
),
msg
);
}
// The set reduces to zero valid elements.
this.reduction = $([]);
}
}
return this;
},
// Validate that the numeric sum of all values is equal to a given value.
sum:function(sum, msg) {
// If a reduced set is attached, use it. Also, remove unsupported
// elements.
var $reduction = (this.reduction || this).filter($.validity.settings.elementSupport);
if ($reduction.length && sum != numericSum($reduction)) {
raiseAggregateError(
$reduction,
msg || format(
$.validity.messages.sum,
{ sum:sum }
)
);
// The set reduces to zero valid elements.
this.reduction = $([]);
}
return this;
},
// Validates an inclusive upper-bound on the numeric sum of the values of
// all matched elements.
sumMax:function(max, msg) {
// If a reduced set is attached, use it. Also, remove unsupported
// elements.
var $reduction = (this.reduction || this).filter($.validity.settings.elementSupport);
if ($reduction.length && max < numericSum($reduction)) {
raiseAggregateError(
$reduction,
msg || format(
$.validity.messages.sumMax,
{ max:max }
)
);
// The set reduces to zero valid elements.
this.reduction = $([]);
}
return this;
},
// Validates an inclusive lower-bound on the numeric sum of the values of
// all matched elements.
sumMin:function(min, msg) {
// If a reduced set is attached, use it. Also, remove unsupported
// elements.
var $reduction = (this.reduction || this).filter($.validity.settings.elementSupport);
if ($reduction.length && min > numericSum($reduction)) {
raiseAggregateError(
$reduction,
msg || format(
$.validity.messages.sumMin,
{ min:min }
)
);
// The set reduces to zero valid elements.
this.reduction = $([]);
}
return this;
},
// Radio group validators:
///////////////////////////////////////////////////////////////////////////
radioChecked:function(val, msg) {
// If a reduced set is attached, use it. Also, remove unsupported
// elements.
var $reduction = (this.reduction || this).filter($.validity.settings.elementSupport);
if ($reduction.is(":radio") && $reduction.find(":checked").val() != val) {
raiseAggregateError(
$reduction,
msg || $.validity.messages.radioChecked
);
}
},
radioNotChecked:function(val, msg) {
// If a reduced set is attached, use it. Also, remove unsupported
// elements.
var $reduction = (this.reduction || this).filter($.validity.settings.elementSupport);
if ($reduction.is(":radio") && $reduction.filter(":checked").val() == val) {
raiseAggregateError(
$reduction,
msg || $.validity.messages.radioChecked
);
}
},
// Checkbox validators:
///////////////////////////////////////////////////////////////////////////
checkboxChecked:function(msg) {
// If a reduced set is attached, use it. Also, remove unsupported
// elements.
var $reduction = (this.reduction || this).filter($.validity.settings.elementSupport);
if ($reduction.is(":checkbox") && !$reduction.is(":checked")) {
raiseAggregateError(
$reduction,
msg || $.validity.messages.radioChecked
);
}
},
// Specialized validators:
///////////////////////////////////////////////////////////////////////////
// If expression is a function, it will be called on each matched element.
// Otherwise, it is treated as a boolean, and the determines the validity
// of elements in an aggregate fashion.
assert:function(expression, msg) {
// If a reduced set is attached, use it. Do not reduce to supported
// elements.
var $reduction = this.reduction || this;
if ($reduction.length) {
// In the case that 'expression' is a function, use it as a
// regimen on each matched element individually:
if ($.isFunction(expression)) {
return validate(
this,
expression,
msg || $.validity.messages.generic
);
}
// Otherwise map it to a boolean and consider this as an aggregate
// validation:
else if (!expression) {
raiseAggregateError(
$reduction,
msg || $.validity.messages.generic
);
// The set reduces to zero valid elements.
this.reduction = $([]);
}
}
return this;
},
fail:function(msg) {
return this.assert(false, msg);
}
});
// Private utilities:
///////////////////////////////////////////////////////////////////////////////
// Do non-aggregate validation. Subject each element in $obj to the regimen.
// Raise the specified error on failures. This function is the heart of
// validity:
function validate($obj, regimen, message) {
var
// If a reduced set is attached, use it Also, remove any unsupported
// elements.
$reduction = ($obj.reduction || $obj).filter($.validity.settings.elementSupport),
// Array to store only elements that pass the regimen.
elements = [];
// For each in the reduction.
$reduction.each(
function() {
// If the element passes the regimen, include it in the reduction.
if (regimen(this)) {
elements.push(this);
}
// Else give the element an error message.
else {
raiseError(
this,
format(message, {
field:infer(this)
})
);
}
}
);
// Attach a (potentially) reduced set of only elements that passed.
$obj.reduction = $(elements);
// Return the full set with attached reduction.
return $obj;
}
// Inform the report object that there was a failure.
function addToReport() {
if ($.validity.isValidating()) {
$.validity.report.errors++;
$.validity.report.valid = false;
}
}
// Inform the report of a failure and display an error according to the idiom
// of the current output mode.
function raiseError(obj, msg) {
addToReport();
$.validity.out.raise($(obj), msg);
}
// Inform the report of a failure and display an aggregate error according to
// the idiom of the current output mode.
function raiseAggregateError($obj, msg) {
addToReport();
$.validity.out.raiseAggregate($obj, msg);
}
// Yield the sum of the values of all fields matched in obj that can be parsed.
function numericSum(obj) {
var accumulator = 0;
obj.each(
function() {
var n = parseFloat(this.value);
accumulator += isNaN(n) ? 0 : n;