forked from posabsolute/jQuery-Validation-Engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.validationEngine.js
2131 lines (1930 loc) · 73.3 KB
/
jquery.validationEngine.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
/*
* Inline Form Validation Engine 2.6.2, jQuery plugin
*
* Copyright(c) 2010, Cedric Dugas
* http://www.position-absolute.com
*
* 2.0 Rewrite by Olivier Refalo
* http://www.crionics.com
*
* Form validation engine allowing custom regex rules to be added.
* Licensed under the MIT License
*/
(function($) {
"use strict";
var methods = {
/**
* Kind of the constructor, called before any action
* @param {Map} user options
*/
init: function(options) {
var form = this;
if (!form.data('jqv') || form.data('jqv') == null ) {
options = methods._saveOptions(form, options);
// bind all formError elements to close on click
$(document).on("click", ".formError", function() {
$(this).fadeOut(150, function() {
// remove prompt once invisible
$(this).closest('.formError').remove();
});
});
}
return this;
},
/**
* Attachs jQuery.validationEngine to form.submit and field.blur events
* Takes an optional params: a list of options
* ie. jQuery("#formID1").validationEngine('attach', {promptPosition : "centerRight"});
*/
attach: function(userOptions) {
var form = this;
var options;
if(userOptions)
options = methods._saveOptions(form, userOptions);
else
options = form.data('jqv');
options.validateAttribute = (form.find("[data-validation-engine*=validate]").length) ? "data-validation-engine" : "class";
if (options.binded) {
// delegate fields
form.on(options.validationEventTrigger, "["+options.validateAttribute+"*=validate]:not([type=checkbox]):not([type=radio]):not(.datepicker)", methods._onFieldEvent);
form.on("click", "["+options.validateAttribute+"*=validate][type=checkbox],["+options.validateAttribute+"*=validate][type=radio]", methods._onFieldEvent);
form.on(options.validationEventTrigger,"["+options.validateAttribute+"*=validate][class*=datepicker]", {"delay": 300}, methods._onFieldEvent);
}
if (options.autoPositionUpdate) {
$(window).bind("resize", {
"noAnimation": true,
"formElem": form
}, methods.updatePromptsPosition);
}
form.on("click","a[data-validation-engine-skip], a[class*='validate-skip'], button[data-validation-engine-skip], button[class*='validate-skip'], input[data-validation-engine-skip], input[class*='validate-skip']", methods._submitButtonClick);
form.removeData('jqv_submitButton');
// bind form.submit
form.on("submit", methods._onSubmitEvent);
return this;
},
/**
* Unregisters any bindings that may point to jQuery.validaitonEngine
*/
detach: function() {
var form = this;
var options = form.data('jqv');
// unbind fields
form.off(options.validationEventTrigger, "["+options.validateAttribute+"*=validate]:not([type=checkbox]):not([type=radio]):not(.datepicker)", methods._onFieldEvent);
form.off("click", "["+options.validateAttribute+"*=validate][type=checkbox],["+options.validateAttribute+"*=validate][type=radio]", methods._onFieldEvent);
form.off(options.validationEventTrigger,"["+options.validateAttribute+"*=validate][class*=datepicker]", methods._onFieldEvent);
// unbind form.submit
form.off("submit", methods._onSubmitEvent);
form.removeData('jqv');
form.off("click", "a[data-validation-engine-skip], a[class*='validate-skip'], button[data-validation-engine-skip], button[class*='validate-skip'], input[data-validation-engine-skip], input[class*='validate-skip']", methods._submitButtonClick);
form.removeData('jqv_submitButton');
if (options.autoPositionUpdate)
$(window).off("resize", methods.updatePromptsPosition);
return this;
},
/**
* Validates either a form or a list of fields, shows prompts accordingly.
* Note: There is no ajax form validation with this method, only field ajax validation are evaluated
*
* @return true if the form validates, false if it fails
*/
validate: function(userOptions) {
var element = $(this);
var valid = null;
var options;
if (element.is("form") || element.hasClass("validationEngineContainer")) {
if (element.hasClass('validating')) {
// form is already validating.
// Should abort old validation and start new one. I don't know how to implement it.
return false;
} else {
element.addClass('validating');
if(userOptions)
options = methods._saveOptions(element, userOptions);
else
options = element.data('jqv');
var valid = methods._validateFields(this);
// If the form doesn't validate, clear the 'validating' class before the user has a chance to submit again
setTimeout(function(){
element.removeClass('validating');
}, 100);
if (valid && options.onSuccess) {
options.onSuccess();
} else if (!valid && options.onFailure) {
options.onFailure();
}
}
} else if (element.is('form') || element.hasClass('validationEngineContainer')) {
element.removeClass('validating');
} else {
// field validation
var form = element.closest('form, .validationEngineContainer');
options = (form.data('jqv')) ? form.data('jqv') : $.validationEngine.defaults;
valid = methods._validateField(element, options);
if (valid && options.onFieldSuccess)
options.onFieldSuccess();
else if (options.onFieldFailure && options.InvalidFields.length > 0) {
options.onFieldFailure();
}
return !valid;
}
if(options.onValidationComplete) {
// !! ensures that an undefined return is interpreted as return false but allows a onValidationComplete() to possibly return true and have form continue processing
return !!options.onValidationComplete(form, valid);
}
return valid;
},
/**
* Redraw prompts position, useful when you change the DOM state when validating
*/
updatePromptsPosition: function(event) {
if (event && this == window) {
var form = event.data.formElem;
var noAnimation = event.data.noAnimation;
}
else
var form = $(this.closest('form, .validationEngineContainer'));
var options = form.data('jqv');
// No option, take default one
if (!options)
options = methods._saveOptions(form, options);
form.find('['+options.validateAttribute+'*=validate]').not(":disabled").each(function(){
var field = $(this);
if (options.prettySelect && field.is(":hidden"))
field = form.find("#" + options.usePrefix + field.attr('id') + options.useSuffix);
var prompt = methods._getPrompt(field);
var promptText = $(prompt).find(".formErrorContent").html();
if(prompt)
methods._updatePrompt(field, $(prompt), promptText, undefined, false, options, noAnimation);
});
return this;
},
/**
* Displays a prompt on a element.
* Note that the element needs an id!
*
* @param {String} promptText html text to display type
* @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red)
* @param {String} possible values topLeft, topRight, bottomLeft, centerRight, bottomRight
*/
showPrompt: function(promptText, type, promptPosition, showArrow) {
var form = this.closest('form, .validationEngineContainer');
var options = form.data('jqv');
// No option, take default one
if(!options)
options = methods._saveOptions(this, options);
if(promptPosition)
options.promptPosition=promptPosition;
options.showArrow = showArrow==true;
methods._showPrompt(this, promptText, type, false, options);
return this;
},
/**
* Closes form error prompts, CAN be invidual
*/
hide: function() {
var form = $(this).closest('form, .validationEngineContainer');
var options = form.data('jqv');
// No option, take default one
if (!options)
options = methods._saveOptions(form, options);
var fadeDuration = (options && options.fadeDuration) ? options.fadeDuration : 0.3;
var closingtag;
if($(this).is("form") || $(this).hasClass("validationEngineContainer")) {
closingtag = "parentForm"+methods._getClassName($(this).attr("id"));
} else {
closingtag = methods._getClassName($(this).attr("id")) +"formError";
}
$('.'+closingtag).fadeTo(fadeDuration, 0, function() {
$(this).closest('.formError').remove();
});
return this;
},
/**
* Closes all error prompts on the page
*/
hideAll: function() {
var form = this;
var options = form.data('jqv');
var duration = options ? options.fadeDuration:300;
$('.formError').fadeTo(duration, 0, function() {
$(this).closest('.formError').remove();
});
return this;
},
/**
* Typically called when user exists a field using tab or a mouse click, triggers a field
* validation
*/
_onFieldEvent: function(event) {
var field = $(this);
var form = field.closest('form, .validationEngineContainer');
var options = form.data('jqv');
// No option, take default one
if (!options)
options = methods._saveOptions(form, options);
options.eventTrigger = "field";
if (options.notEmpty == true){
if(field.val().length > 0){
// validate the current field
window.setTimeout(function() {
methods._validateField(field, options);
}, (event.data) ? event.data.delay : 0);
}
}else{
// validate the current field
window.setTimeout(function() {
methods._validateField(field, options);
}, (event.data) ? event.data.delay : 0);
}
},
/**
* Called when the form is submited, shows prompts accordingly
*
* @param {jqObject}
* form
* @return false if form submission needs to be cancelled
*/
_onSubmitEvent: function() {
var form = $(this);
var options = form.data('jqv');
//check if it is trigger from skipped button
if (form.data("jqv_submitButton")){
var submitButton = $("#" + form.data("jqv_submitButton"));
if (submitButton){
if (submitButton.length > 0){
if (submitButton.hasClass("validate-skip") || submitButton.attr("data-validation-engine-skip") == "true")
return true;
}
}
}
options.eventTrigger = "submit";
// validate each field
// (- skip field ajax validation, not necessary IF we will perform an ajax form validation)
var r=methods._validateFields(form);
if (r && options.ajaxFormValidation) {
methods._validateFormWithAjax(form, options);
// cancel form auto-submission - process with async call onAjaxFormComplete
return false;
}
if(options.onValidationComplete) {
// !! ensures that an undefined return is interpreted as return false but allows a onValidationComplete() to possibly return true and have form continue processing
return !!options.onValidationComplete(form, r);
}
return r;
},
/**
* Return true if the ajax field validations passed so far
* @param {Object} options
* @return true, is all ajax validation passed so far (remember ajax is async)
*/
_checkAjaxStatus: function(options) {
var status = true;
$.each(options.ajaxValidCache, function(key, value) {
if (!value) {
status = false;
// break the each
return false;
}
});
return status;
},
/**
* Return true if the ajax field is validated
* @param {String} fieldid
* @param {Object} options
* @return true, if validation passed, false if false or doesn't exist
*/
_checkAjaxFieldStatus: function(fieldid, options) {
return options.ajaxValidCache[fieldid] == true;
},
/**
* Validates form fields, shows prompts accordingly
*
* @param {jqObject}
* form
* @param {skipAjaxFieldValidation}
* boolean - when set to true, ajax field validation is skipped, typically used when the submit button is clicked
*
* @return true if form is valid, false if not, undefined if ajax form validation is done
*/
_validateFields: function(form) {
var options = form.data('jqv');
// this variable is set to true if an error is found
var errorFound = false;
// Trigger hook, start validation
form.trigger("jqv.form.validating");
// first, evaluate status of non ajax fields
var first_err=null;
form.find('['+options.validateAttribute+'*=validate]').not(":disabled").each( function() {
var field = $(this);
var names = [];
if ($.inArray(field.attr('name'), names) < 0) {
errorFound |= methods._validateField(field, options);
if (errorFound && first_err==null)
if (field.is(":hidden") && options.prettySelect)
first_err = field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix);
else {
//Check if we need to adjust what element to show the prompt on
//and and such scroll to instead
if(field.data('jqv-prompt-at') instanceof jQuery ){
field = field.data('jqv-prompt-at');
} else if(field.data('jqv-prompt-at')) {
field = $(field.data('jqv-prompt-at'));
}
first_err=field;
}
if (options.doNotShowAllErrosOnSubmit)
return false;
names.push(field.attr('name'));
//if option set, stop checking validation rules after one error is found
if(options.showOneMessage == true && errorFound){
return false;
}
}
});
// second, check to see if all ajax calls completed ok
// errorFound |= !methods._checkAjaxStatus(options);
// third, check status and scroll the container accordingly
form.trigger("jqv.form.result", [errorFound]);
if (errorFound) {
if (options.scroll) {
var destination=first_err.offset().top;
var fixleft = first_err.offset().left;
//prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10)
var positionType=options.promptPosition;
if (typeof(positionType)=='string' && positionType.indexOf(":")!=-1)
positionType=positionType.substring(0,positionType.indexOf(":"));
if (positionType!="bottomRight" && positionType!="bottomLeft") {
var prompt_err= methods._getPrompt(first_err);
if (prompt_err) {
destination=prompt_err.offset().top;
}
}
// Offset the amount the page scrolls by an amount in px to accomodate fixed elements at top of page
if (options.scrollOffset) {
destination -= options.scrollOffset;
}
// get the position of the first error, there should be at least one, no need to check this
//var destination = form.find(".formError:not('.greenPopup'):first").offset().top;
if (options.isOverflown) {
var overflowDIV = $(options.overflownDIV);
if(!overflowDIV.length) return false;
var scrollContainerScroll = overflowDIV.scrollTop();
var scrollContainerPos = -parseInt(overflowDIV.offset().top);
destination += scrollContainerScroll + scrollContainerPos - 5;
var scrollContainer = $(options.overflownDIV).filter(":not(:animated)");
scrollContainer.animate({ scrollTop: destination }, 1100, function(){
if(options.focusFirstField) first_err.focus();
});
} else {
$("html, body").animate({
scrollTop: destination
}, 1100, function(){
if(options.focusFirstField) first_err.focus();
});
$("html, body").animate({scrollLeft: fixleft},1100)
}
} else if(options.focusFirstField)
first_err.focus();
return false;
}
return true;
},
/**
* This method is called to perform an ajax form validation.
* During this process all the (field, value) pairs are sent to the server which returns a list of invalid fields or true
*
* @param {jqObject} form
* @param {Map} options
*/
_validateFormWithAjax: function(form, options) {
var data = form.serialize();
var type = (options.ajaxFormValidationMethod) ? options.ajaxFormValidationMethod : "GET";
var url = (options.ajaxFormValidationURL) ? options.ajaxFormValidationURL : form.attr("action");
var dataType = (options.dataType) ? options.dataType : "json";
$.ajax({
type: type,
url: url,
cache: false,
dataType: dataType,
data: data,
form: form,
methods: methods,
options: options,
beforeSend: function() {
return options.onBeforeAjaxFormValidation(form, options);
},
error: function(data, transport) {
if (options.onFailure) {
options.onFailure(data, transport);
} else {
methods._ajaxError(data, transport);
}
},
success: function(json) {
if ((dataType == "json") && (json !== true)) {
// getting to this case doesn't necessary means that the form is invalid
// the server may return green or closing prompt actions
// this flag helps figuring it out
var errorInForm=false;
for (var i = 0; i < json.length; i++) {
var value = json[i];
var errorFieldId = value[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
// promptText or selector
var msg = value[2];
// if the field is valid
if (value[1] == true) {
if (msg == "" || !msg){
// if for some reason, status==true and error="", just close the prompt
methods._closePrompt(errorField);
} else {
// the field is valid, but we are displaying a green prompt
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt)
msg = txt;
}
if (options.showPrompts) methods._showPrompt(errorField, msg, "pass", false, options, true);
}
} else {
// the field is invalid, show the red error prompt
errorInForm|=true;
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt)
msg = txt;
}
if(options.showPrompts) methods._showPrompt(errorField, msg, "", false, options, true);
}
}
}
options.onAjaxFormComplete(!errorInForm, form, json, options);
} else
options.onAjaxFormComplete(true, form, json, options);
}
});
},
/**
* Validates field, shows prompts accordingly
*
* @param {jqObject}
* field
* @param {Array[String]}
* field's validation rules
* @param {Map}
* user options
* @return false if field is valid (It is inversed for *fields*, it return false on validate and true on errors.)
*/
_validateField: function(field, options, skipAjaxValidation) {
if (!field.attr("id")) {
field.attr("id", "form-validation-field-" + $.validationEngine.fieldIdCounter);
++$.validationEngine.fieldIdCounter;
}
if(field.hasClass(options.ignoreFieldsWithClass))
return false;
if (!options.validateNonVisibleFields && (field.is(":hidden") && !options.prettySelect || field.parent().is(":hidden")))
return false;
var rulesParsing = field.attr(options.validateAttribute);
var getRules = /validate\[(.*)\]/.exec(rulesParsing);
if (!getRules)
return false;
var str = getRules[1];
var rules = str.split(/\[|,|\]/);
// true if we ran the ajax validation, tells the logic to stop messing with prompts
var isAjaxValidator = false;
var fieldName = field.attr("name");
var promptText = "";
var promptType = "";
var required = false;
var limitErrors = false;
options.isError = false;
options.showArrow = true;
// If the programmer wants to limit the amount of error messages per field,
if (options.maxErrorsPerField > 0) {
limitErrors = true;
}
var form = $(field.closest("form, .validationEngineContainer"));
// Fix for adding spaces in the rules
for (var i = 0; i < rules.length; i++) {
rules[i] = rules[i].replace(" ", "");
// Remove any parsing errors
if (rules[i] === '') {
delete rules[i];
}
}
for (var i = 0, field_errors = 0; i < rules.length; i++) {
// If we are limiting errors, and have hit the max, break
if (limitErrors && field_errors >= options.maxErrorsPerField) {
// If we haven't hit a required yet, check to see if there is one in the validation rules for this
// field and that it's index is greater or equal to our current index
if (!required) {
var have_required = $.inArray('required', rules);
required = (have_required != -1 && have_required >= i);
}
break;
}
var errorMsg = undefined;
switch (rules[i]) {
case "required":
required = true;
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._required);
break;
case "custom":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._custom);
break;
case "groupRequired":
// Check is its the first of group, if not, reload validation with first field
// AND continue normal validation on present field
var classGroup = "["+options.validateAttribute+"*=" +rules[i + 1] +"]";
var firstOfGroup = form.find(classGroup).eq(0);
if(firstOfGroup[0] != field[0]){
methods._validateField(firstOfGroup, options, skipAjaxValidation);
options.showArrow = true;
}
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._groupRequired);
if(errorMsg) required = true;
options.showArrow = false;
break;
case "ajax":
// AJAX defaults to returning it's loading message
errorMsg = methods._ajax(field, rules, i, options);
if (errorMsg) {
promptType = "load";
}
break;
case "minSize":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minSize);
break;
case "maxSize":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxSize);
break;
case "min":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._min);
break;
case "max":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._max);
break;
case "past":
errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._past);
break;
case "future":
errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._future);
break;
case "dateRange":
var classGroup = "["+options.validateAttribute+"*=" + rules[i + 1] + "]";
options.firstOfGroup = form.find(classGroup).eq(0);
options.secondOfGroup = form.find(classGroup).eq(1);
//if one entry out of the pair has value then proceed to run through validation
if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) {
errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._dateRange);
}
if (errorMsg) required = true;
options.showArrow = false;
break;
case "dateTimeRange":
var classGroup = "["+options.validateAttribute+"*=" + rules[i + 1] + "]";
options.firstOfGroup = form.find(classGroup).eq(0);
options.secondOfGroup = form.find(classGroup).eq(1);
//if one entry out of the pair has value then proceed to run through validation
if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) {
errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._dateTimeRange);
}
if (errorMsg) required = true;
options.showArrow = false;
break;
case "maxCheckbox":
field = $(form.find("input[name='" + fieldName + "']"));
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxCheckbox);
break;
case "minCheckbox":
field = $(form.find("input[name='" + fieldName + "']"));
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minCheckbox);
break;
case "equals":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._equals);
break;
case "funcCall":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._funcCall);
break;
case "creditCard":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._creditCard);
break;
case "condRequired":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._condRequired);
if (errorMsg !== undefined) {
required = true;
}
break;
case "funcCallRequired":
errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._funcCallRequired);
if (errorMsg !== undefined) {
required = true;
}
break;
default:
}
var end_validation = false;
// If we were passed back an message object, check what the status was to determine what to do
if (typeof errorMsg == "object") {
switch (errorMsg.status) {
case "_break":
end_validation = true;
break;
// If we have an error message, set errorMsg to the error message
case "_error":
errorMsg = errorMsg.message;
break;
// If we want to throw an error, but not show a prompt, return early with true
case "_error_no_prompt":
return true;
break;
// Anything else we continue on
default:
break;
}
}
//funcCallRequired, first in rules, and has error, skip anything else
if( i==0 && str.indexOf('funcCallRequired')==0 && errorMsg !== undefined ){
promptText += errorMsg + "<br/>";
options.isError=true;
field_errors++;
end_validation=true;
}
// If it has been specified that validation should end now, break
if (end_validation) {
break;
}
// If we have a string, that means that we have an error, so add it to the error message.
if (typeof errorMsg == 'string') {
promptText += errorMsg + "<br/>";
options.isError = true;
field_errors++;
}
}
// If the rules required is not added, an empty field is not validated
//the 3rd condition is added so that even empty password fields should be equal
//otherwise if one is filled and another left empty, the "equal" condition would fail
//which does not make any sense
if(!required && !(field.val()) && field.val().length < 1 && $.inArray('equals', rules) < 0) options.isError = false;
// Hack for radio/checkbox group button, the validation go into the
// first radio/checkbox of the group
var fieldType = field.prop("type");
var positionType=field.data("promptPosition") || options.promptPosition;
if ((fieldType == "radio" || fieldType == "checkbox") && form.find("input[name='" + fieldName + "']").size() > 1) {
if(positionType === 'inline') {
field = $(form.find("input[name='" + fieldName + "'][type!=hidden]:last"));
} else {
field = $(form.find("input[name='" + fieldName + "'][type!=hidden]:first"));
}
options.showArrow = options.showArrowOnRadioAndCheckbox;
}
if(field.is(":hidden") && options.prettySelect) {
field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix);
}
if (options.isError && options.showPrompts){
methods._showPrompt(field, promptText, promptType, false, options);
}else{
if (!isAjaxValidator) methods._closePrompt(field);
}
if (!isAjaxValidator) {
field.trigger("jqv.field.result", [field, options.isError, promptText]);
}
/* Record error */
var errindex = $.inArray(field[0], options.InvalidFields);
if (errindex == -1) {
if (options.isError)
options.InvalidFields.push(field[0]);
} else if (!options.isError) {
options.InvalidFields.splice(errindex, 1);
}
methods._handleStatusCssClasses(field, options);
/* run callback function for each field */
if (options.isError && options.onFieldFailure)
options.onFieldFailure(field);
if (!options.isError && options.onFieldSuccess)
options.onFieldSuccess(field);
return options.isError;
},
/**
* Handling css classes of fields indicating result of validation
*
* @param {jqObject}
* field
* @param {Array[String]}
* field's validation rules
* @private
*/
_handleStatusCssClasses: function(field, options) {
/* remove all classes */
if(options.addSuccessCssClassToField)
field.removeClass(options.addSuccessCssClassToField);
if(options.addFailureCssClassToField)
field.removeClass(options.addFailureCssClassToField);
/* Add classes */
if (options.addSuccessCssClassToField && !options.isError)
field.addClass(options.addSuccessCssClassToField);
if (options.addFailureCssClassToField && options.isError)
field.addClass(options.addFailureCssClassToField);
},
/********************
* _getErrorMessage
*
* @param form
* @param field
* @param rule
* @param rules
* @param i
* @param options
* @param originalValidationMethod
* @return {*}
* @private
*/
_getErrorMessage:function (form, field, rule, rules, i, options, originalValidationMethod) {
// If we are using the custon validation type, build the index for the rule.
// Otherwise if we are doing a function call, make the call and return the object
// that is passed back.
var rule_index = jQuery.inArray(rule, rules);
if (rule === "custom" || rule === "funcCall" || rule === "funcCallRequired") {
var custom_validation_type = rules[rule_index + 1];
rule = rule + "[" + custom_validation_type + "]";
// Delete the rule from the rules array so that it doesn't try to call the
// same rule over again
delete(rules[rule_index]);
}
// Change the rule to the composite rule, if it was different from the original
var alteredRule = rule;
var element_classes = (field.attr("data-validation-engine")) ? field.attr("data-validation-engine") : field.attr("class");
var element_classes_array = element_classes.split(" ");
// Call the original validation method. If we are dealing with dates or checkboxes, also pass the form
var errorMsg;
if (rule == "future" || rule == "past" || rule == "maxCheckbox" || rule == "minCheckbox") {
errorMsg = originalValidationMethod(form, field, rules, i, options);
} else {
errorMsg = originalValidationMethod(field, rules, i, options);
}
// If the original validation method returned an error and we have a custom error message,
// return the custom message instead. Otherwise return the original error message.
if (errorMsg != undefined) {
var custom_message = methods._getCustomErrorMessage($(field), element_classes_array, alteredRule, options);
if (custom_message) errorMsg = custom_message;
}
return errorMsg;
},
_getCustomErrorMessage:function (field, classes, rule, options) {
var custom_message = false;
var validityProp = /^custom\[.*\]$/.test(rule) ? methods._validityProp["custom"] : methods._validityProp[rule];
// If there is a validityProp for this rule, check to see if the field has an attribute for it
if (validityProp != undefined) {
custom_message = field.attr("data-errormessage-"+validityProp);
// If there was an error message for it, return the message
if (custom_message != undefined)
return custom_message;
}
custom_message = field.attr("data-errormessage");
// If there is an inline custom error message, return it
if (custom_message != undefined)
return custom_message;
var id = '#' + field.attr("id");
// If we have custom messages for the element's id, get the message for the rule from the id.
// Otherwise, if we have custom messages for the element's classes, use the first class message we find instead.
if (typeof options.custom_error_messages[id] != "undefined" &&
typeof options.custom_error_messages[id][rule] != "undefined" ) {
custom_message = options.custom_error_messages[id][rule]['message'];
} else if (classes.length > 0) {
for (var i = 0; i < classes.length && classes.length > 0; i++) {
var element_class = "." + classes[i];
if (typeof options.custom_error_messages[element_class] != "undefined" &&
typeof options.custom_error_messages[element_class][rule] != "undefined") {
custom_message = options.custom_error_messages[element_class][rule]['message'];
break;
}
}
}
if (!custom_message &&
typeof options.custom_error_messages[rule] != "undefined" &&
typeof options.custom_error_messages[rule]['message'] != "undefined"){
custom_message = options.custom_error_messages[rule]['message'];
}
return custom_message;
},
_validityProp: {
"required": "value-missing",
"custom": "custom-error",
"groupRequired": "value-missing",
"ajax": "custom-error",
"minSize": "range-underflow",
"maxSize": "range-overflow",
"min": "range-underflow",
"max": "range-overflow",
"past": "type-mismatch",
"future": "type-mismatch",
"dateRange": "type-mismatch",
"dateTimeRange": "type-mismatch",
"maxCheckbox": "range-overflow",
"minCheckbox": "range-underflow",
"equals": "pattern-mismatch",
"funcCall": "custom-error",
"funcCallRequired": "custom-error",
"creditCard": "pattern-mismatch",
"condRequired": "value-missing"
},
/**
* Required validation
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @param {bool} condRequired flag when method is used for internal purpose in condRequired check
* @return an error string if validation failed
*/
_required: function(field, rules, i, options, condRequired) {
switch (field.prop("type")) {
case "radio":
case "checkbox":
// new validation style to only check dependent field
if (condRequired) {
if (!field.prop('checked')) {
return options.allrules[rules[i]].alertTextCheckboxMultiple;
}
break;
}
// old validation style
var form = field.closest("form, .validationEngineContainer");
var name = field.attr("name");
if (form.find("input[name='" + name + "']:checked").size() == 0) {
if (form.find("input[name='" + name + "']:visible").size() == 1)
return options.allrules[rules[i]].alertTextCheckboxe;
else
return options.allrules[rules[i]].alertTextCheckboxMultiple;
}
break;
case "text":
case "password":
case "textarea":
case "file":
case "select-one":
case "select-multiple":
default:
var field_val = $.trim( field.val() );
var dv_placeholder = $.trim( field.attr("data-validation-placeholder") );
var placeholder = $.trim( field.attr("placeholder") );
if (
( !field_val )
|| ( dv_placeholder && field_val == dv_placeholder )
|| ( placeholder && field_val == placeholder )
) {
return options.allrules[rules[i]].alertText;
}
break;
}
},
/**
* Validate that 1 from the group field is required
*
* @param {jqObject} field
* @param {Array[String]} rules
* @param {int} i rules index
* @param {Map}
* user options
* @return an error string if validation failed
*/
_groupRequired: function(field, rules, i, options) {
var classGroup = "["+options.validateAttribute+"*=" +rules[i + 1] +"]";