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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
|
/**
* Prado client-side javascript validation fascade.
*
* There are 4 basic classes, Validation, ValidationManager, ValidationSummary
* and TBaseValidator, that interact together to perform validation.
* The <tt>Prado.Validation</tt> class co-ordinates together the
* validation scheme and is responsible for maintaining references
* to ValidationManagers.
*
* The ValidationManager class is responsible for maintaining refereneces
* to individual validators, validation summaries and their associated
* groupings.
*
* The ValidationSummary take cares of display the validator error messages
* as html output or an alert output.
*
* The TBaseValidator is the base class for all validators and contains
* methods to interact with the actual inputs, data type conversion.
*
* An instance of ValidationManager must be instantiated first for a
* particular form before instantiating validators and summaries.
*
* Usage example: adding a required field to a text box input with
* ID "input1" in a form with ID "form1".
* <code>
* <script type="text/javascript" src="../prado.js"></script>
* <script type="text/javascript" src="../validator.js"></script>
* <form id="form1" action="...">
* <div>
* <input type="text" id="input1" />
* <span id="validator1" style="display:none; color:red">*</span>
* <input type="submit text="submit" />
* <script type="text/javascript">
* new Prado.ValidationManager({FormID : 'form1'});
* var options =
* {
* ID : 'validator1',
* FormID : 'form1',
* ErrorMessage : '*',
* ControlToValidate : 'input1'
* }
* new Prado.WebUI.TRequiredFieldValidator(options);
* new Prado.WebUI.TValidationSummary({ID:'summary1',FormID:'form1'});
*
* //watch the form onsubmit event, check validators, stop if not valid.
* Event.observe("form1", "submit" function(ev)
* {
* if(Prado.WebUI.Validation.isValid("form1") == false)
* Event.stop(ev);
* });
* </script>
* </div>
* </form>
* </code>
*/
Prado.Validation = Class.create();
/**
* A global validation manager.
* To validate the inputs of a particular form, call
* <code>Prado.Validation.validate(formID, groupID)</code>
* where <tt>formID</tt> is the HTML form ID, and the optional
* <tt>groupID</tt> if present will only validate the validators
* in a particular group.
*/
Object.extend(Prado.Validation,
{
managers : {},
/**
* Validate the validators (those that <strong>DO NOT</strong>
* belong to a particular group) the form specified by the
* <tt>formID</tt> parameter. If <tt>groupID</tt> is specified
* then only validators belonging to that group will be validated.
* @param string ID of the form to validate
* @param string ID of the group to validate.
* @param HTMLElement element that calls for validation
*/
validate : function(formID, groupID, invoker)
{
if(this.managers[formID])
{
return this.managers[formID].validate(groupID, invoker);
}
else
{
throw new Error("Form '"+form+"' is not registered with Prado.Validation");
}
},
/**
* Check if the validators are valid for a particular form (and group).
* The validators states will not be changed.
* The <tt>validate</tt> function should be called first.
* @param string ID of the form to validate
* @param string ID of the group to validate.
*/
isValid : function(formID, groupID)
{
if(this.managers[formID])
return this.managers[formID].isValid(groupID);
return true;
},
/**
* Add a new validator to a particular form.
* @param string the form that the validator belongs.
* @param object a validator
* @return object the manager
*/
addValidator : function(formID, validator)
{
if(this.managers[formID])
this.managers[formID].addValidator(validator);
else
throw new Error("A validation manager for form '"+formID+"' needs to be created first.");
return this.managers[formID];
},
/**
* Add a new validation summary.
* @param string the form that the validation summary belongs.
* @param object a validation summary
* @return object manager
*/
addSummary : function(formID, validator)
{
if(this.managers[formID])
this.managers[formID].addSummary(validator);
else
throw new Error("A validation manager for form '"+formID+"' needs to be created first.");
return this.managers[formID];
}
});
Prado.ValidationManager = Class.create();
/**
* Validation manager instances. Manages validators for a particular
* HTML form. The manager contains references to all the validators
* summaries, and their groupings for a particular form.
* Generally, <tt>Prado.Validation</tt> methods should be called rather
* than calling directly the ValidationManager.
*/
Prado.ValidationManager.prototype =
{
validators : [], // list of validators
summaries : [], // validation summaries
groups : [], // validation groups
options : {},
/**
* <code>
* options['FormID']* The ID of HTML form to manage.
* </code>
*/
initialize : function(options)
{
this.options = options;
Prado.Validation.managers[options.FormID] = this;
},
/**
* Validate the validators managed by this validation manager.
* @param string only validate validators belonging to a group (optional)
* @param HTMLElement element that calls for validation
* @return boolean true if all validators are valid, false otherwise.
*/
validate : function(group, invoker)
{
if(group)
return this._validateGroup(group, invoker);
else
return this._validateNonGroup(invoker);
},
/**
* Validate a particular group of validators.
* @param string ID of the form
* @param HTMLElement element that calls for validation
* @return boolean false if group is not valid, true otherwise.
*/
_validateGroup: function(groupID, invoker)
{
var valid = true;
if(this.groups.include(groupID))
{
this.validators.each(function(validator)
{
if(validator.group == groupID)
valid = valid & validator.validate(invoker);
else
validator.hide();
});
}
this.updateSummary(groupID, true);
return valid;
},
/**
* Validate validators that doesn't belong to any group.
* @return boolean false if not valid, true otherwise.
* @param HTMLElement element that calls for validation
*/
_validateNonGroup : function(invoker)
{
var valid = true;
this.validators.each(function(validator)
{
if(!validator.group)
valid = valid & validator.validate(invoker);
else
validator.hide();
});
this.updateSummary(null, true);
return valid;
},
/**
* Gets the state of all the validators, true if they are all valid.
* @return boolean true if the validators are valid.
*/
isValid : function(group)
{
if(group)
return this._isValidGroup(group);
else
return this._isValidNonGroup();
},
/**
* @return boolean true if all validators not belonging to a group are valid.
*/
_isValidNonGroup : function()
{
var valid = true;
this.validators.each(function(validator)
{
if(!validator.group)
valid = valid & validator.isValid;
});
return valid;
},
/**
* @return boolean true if all validators belonging to the group are valid.
*/
_isValidGroup : function(groupID)
{
var valid = true;
if(this.groups.include(groupID))
{
this.validators.each(function(validator)
{
if(validator.group == groupID)
valid = valid & validator.isValid;
});
}
return valid;
},
/**
* Add a validator to this manager.
* @param Prado.WebUI.TBaseValidator a new validator
*/
addValidator : function(validator)
{
this.validators.push(validator);
if(validator.group && !this.groups.include(validator.group))
this.groups.push(validator.group);
},
/**
* Add a validation summary.
* @param Prado.WebUI.TValidationSummary validation summary.
*/
addSummary : function(summary)
{
this.summaries.push(summary);
},
/**
* Gets all validators that belong to a group or that the validator
* group is null and the validator validation was false.
* @return array list of validators with error.
*/
getValidatorsWithError : function(group)
{
var validators = this.validators.findAll(function(validator)
{
var notValid = !validator.isValid;
var inGroup = group && validator.group == group;
var noGroup = validator.group == null;
return notValid && (inGroup || noGroup);
});
return validators;
},
/**
* Update the summary of a particular group.
* @param string validation group to update.
*/
updateSummary : function(group, refresh)
{
var validators = this.getValidatorsWithError(group);
this.summaries.each(function(summary)
{
var inGroup = group && summary.group == group;
var noGroup = !group && !summary.group;
if(inGroup || noGroup)
summary.updateSummary(validators, refresh);
else
summary.hideSummary(true);
});
}
};
/**
* TValidationSummary displays a summary of validation errors inline on a Web page,
* in a message box, or both. By default, a validation summary will collect
* <tt>ErrorMessage</tt> of all failed validators on the page. If
* <tt>ValidationGroup</tt> is not empty, only those validators who belong
* to the group will show their error messages in the summary.
*
* The summary can be displayed as a list, as a bulleted list, or as a single
* paragraph based on the <tt>DisplayMode</tt> option.
* The messages shown can be prefixed with <tt>HeaderText</tt>.
*
* The summary can be displayed on the Web page and in a message box by setting
* the <tt>ShowSummary</tt> and <tt>ShowMessageBox</tt>
* options, respectively.
*/
Prado.WebUI.TValidationSummary = Class.create();
Prado.WebUI.TValidationSummary.prototype =
{
group : null,
options : {},
visible : false,
messages : null,
/**
* <code>
* options['ID']* Validation summary ID, i.e., an HTML element ID
* options['FormID']* HTML form that this summary belongs.
* options['ShowMessageBox'] True to show the summary in an alert box.
* options['ShowSummary'] True to show the inline summary.
* options['HeaderText'] Summary header text
* options['DisplayMode'] Summary display style, 'BulletList', 'List', 'SingleParagraph'
* options['Refresh'] True to update the summary upon validator state change.
* options['ValidationGroup'] Validation summary group
* options['Display'] Display mode, 'None', 'Static', 'Dynamic'.
* options['ScrollToSummary'] True to scroll to the validation summary upon refresh.
* </code>
*/
initialize : function(options)
{
this.options = options;
this.group = options.ValidationGroup;
this.messages = $(options.ID);
this.visible = this.messages.style.visibility != "hidden"
this.visible = this.visible && this.messages.style.display != "none";
Prado.Validation.addSummary(options.FormID, this);
},
/**
* Update the validation summary to show the error message from
* validators that failed validation.
* @param array list of validators that failed validation.
* @param boolean update the summary;
*/
updateSummary : function(validators, update)
{
if(validators.length <= 0)
{
if(update || this.options.Refresh != false)
{
return this.hideSummary(validators);
}
return;
}
var refresh = update || this.visible == false || this.options.Refresh != false;
if(this.options.ShowSummary != false && refresh)
{
this.updateHTMLMessages(this.getMessages(validators));
this.showSummary(validators);
}
if(this.options.ScrollToSummary != false)
window.scrollTo(this.messages.offsetLeft-20, this.messages.offsetTop-20);
if(this.options.ShowMessageBox == true && refresh)
{
this.alertMessages(this.getMessages(validators));
this.visible = true;
}
},
/**
* Display the validator error messages as inline HTML.
*/
updateHTMLMessages : function(messages)
{
while(this.messages.childNodes.length > 0)
this.messages.removeChild(this.messages.lastChild);
new Insertion.Bottom(this.messages, this.formatSummary(messages));
},
/**
* Display the validator error messages as an alert box.
*/
alertMessages : function(messages)
{
var text = this.formatMessageBox(messages);
setTimeout(function(){ alert(text); },20);
},
/**
* @return array list of validator error messages.
*/
getMessages : function(validators)
{
var messages = [];
validators.each(function(validator)
{
var message = validator.getErrorMessage();
if(typeof(message) == 'string' && message.length > 0)
messages.push(message);
})
return messages;
},
/**
* Hides the validation summary.
*/
hideSummary : function(validators)
{ if(typeof(this.options.OnHideSummary) == "function")
{
this.messages.style.visibility="visible";
this.options.OnHideSummary(this,validators)
}
else
{
this.messages.style.visibility="hidden";
if(this.options.Display == "None" || this.options.Display == "Dynamic")
this.messages.hide();
}
this.visible = false;
},
/**
* Shows the validation summary.
*/
showSummary : function(validators)
{
this.messages.style.visibility="visible";
if(typeof(this.options.OnShowSummary) == "function")
this.options.OnShowSummary(this,validators);
else
this.messages.show();
this.visible = true;
},
/**
* Return the format parameters for the summary.
* @param string format type, "List", "SingleParagraph" or "BulletList"
* @type array formatting parameters
*/
formats : function(type)
{
switch(type)
{
case "List":
return { header : "<br />", first : "", pre : "", post : "<br />", last : ""};
case "SingleParagraph":
return { header : " ", first : "", pre : "", post : " ", last : "<br />"};
case "BulletList":
default:
return { header : "", first : "<ul>", pre : "<li>", post : "</li>", last : "</ul>"};
}
},
/**
* Format the message summary.
* @param array list of error messages.
* @type string formatted message
*/
formatSummary : function(messages)
{
var format = this.formats(this.options.DisplayMode);
var output = this.options.HeaderText ? this.options.HeaderText + format.header : "";
output += format.first;
messages.each(function(message)
{
output += message.length > 0 ? format.pre + message + format.post : "";
});
// for(var i = 0; i < messages.length; i++)
// output += (messages[i].length>0) ? format.pre + messages[i] + format.post : "";
output += format.last;
return output;
},
/**
* Format the message alert box.
* @param array a list of error messages.
* @type string format message for alert.
*/
formatMessageBox : function(messages)
{
var output = this.options.HeaderText ? this.options.HeaderText + "\n" : "";
for(var i = 0; i < messages.length; i++)
{
switch(this.options.DisplayMode)
{
case "List":
output += messages[i] + "\n";
break;
case "BulletList":
default:
output += " - " + messages[i] + "\n";
break;
case "SingleParagraph":
output += messages[i] + " ";
break;
}
}
return output;
}
};
/**
* TBaseValidator serves as the base class for validator controls.
*
* Validation is performed when a postback control, such as a TButton,
* a TLinkButton or a TTextBox (under AutoPostBack mode) is submitting
* the page and its <tt>CausesValidation</tt> option is true.
* The input control to be validated is specified by <tt>ControlToValidate</tt>
* option.
*/
Prado.WebUI.TBaseValidator = Class.create();
Prado.WebUI.TBaseValidator.prototype =
{
enabled : true,
visible : false,
isValid : true,
options : {},
_isObserving : {},
group : null,
manager : null,
message : null,
/**
* <code>
* options['ID']* Validator ID, e.g. span with message
* options['FormID']* HTML form that the validator belongs
* options['ControlToValidate']*HTML form input to validate
* options['Display'] Display mode, 'None', 'Static', 'Dynamic'
* options['ErrorMessage'] Validation error message
* options['FocusOnError'] True to focus on validation error
* options['FocusElementID'] Element to focus on error
* options['ValidationGroup'] Validation group
* options['ControlCssClass'] Css class to use on the input upon error
* options['OnValidate'] Function to call immediately after validation
* options['OnSuccess'] Function to call upon after successful validation
* options['OnError'] Function to call upon after error in validation.
* options['ObserveChanges'] True to observe changes in input
* </code>
*/
initialize : function(options)
{
/* options.OnValidate = options.OnValidate || Prototype.emptyFunction;
options.OnSuccess = options.OnSuccess || Prototype.emptyFunction;
options.OnError = options.OnError || Prototype.emptyFunction;
*/
this.options = options;
this.control = $(options.ControlToValidate);
this.message = $(options.ID);
this.group = options.ValidationGroup;
this.manager = Prado.Validation.addValidator(options.FormID, this);
},
/**
* @return string validation error message.
*/
getErrorMessage : function()
{
return this.options.ErrorMessage;
},
/**
* Update the validator span, input CSS class, and focus particular
* element. Updating the validator control will set the validator
* <tt>visible</tt> property to true.
*/
updateControl: function()
{
if(this.message)
{
if(this.options.Display == "Dynamic")
this.isValid ? this.message.hide() : this.message.show();
this.message.style.visibility = this.isValid ? "hidden" : "visible";
}
if(this.control)
this.updateControlCssClass(this.control, this.isValid);
if(this.options.FocusOnError && !this.isValid)
Prado.Element.focus(this.options.FocusElementID);
this.visible = true;
},
/**
* Add a css class to the input control if validator is invalid,
* removes the css class if valid.
* @param object html control element
* @param boolean true to remove the css class, false to add.
*/
updateControlCssClass : function(control, valid)
{
var CssClass = this.options.ControlCssClass;
if(typeof(CssClass) == "string" && CssClass.length > 0)
{
if(valid)
control.removeClassName(CssClass);
else
control.addClassName(CssClass);
}
},
/**
* Hides the validator messages and remove any validation changes.
*/
hide : function()
{
this.isValid = true;
this.updateControl();
this.visible = false;
},
/**
* Calls evaluateIsValid() function to set the value of isValid property.
* Triggers onValidate event and onSuccess or onError event.
* @param HTMLElement element that calls for validation
* @return boolean true if valid.
*/
validate : function(invoker)
{
if(typeof(this.options.OnValidate) == "function")
this.options.OnValidate(this, invoker);
if(this.enabled)
this.isValid = this.evaluateIsValid();
if(this.isValid)
{
if(typeof(this.options.OnSuccess) == "function")
{
this.visible = true;
this.message.style.visibility = "visible";
this.updateControlCssClass(this.control, this.isValid);
this.options.OnSuccess(this, invoker);
}
else
this.updateControl();
}
else
{
if(typeof(this.options.OnError) == "function")
{
this.visible = true;
this.message.style.visibility = "visible";
this.updateControlCssClass(this.control, this.isValid);
this.options.OnError(this, invoker);
}
else
this.updateControl();
}
this.observeChanges(this.control);
return this.isValid;
},
/**
* Observe changes to the control input, re-validate upon change. If
* the validator is not visible, no updates are propagated.
* @param HTMLElement element that calls for validation
*/
observeChanges : function(control)
{
if(!control) return;
var canObserveChanges = this.options.ObserveChanges != false;
var currentlyObserving = this._isObserving[control.id+this.options.ID];
if(canObserveChanges && !currentlyObserving)
{
var validator = this;
Event.observe(control, 'change', function()
{
if(validator.visible)
{
validator.validate();
validator.manager.updateSummary(validator.group);
}
});
this._isObserving[control.id+this.options.ID] = true;
}
},
/**
* @return string trims the string value, empty string if value is not string.
*/
trim : function(value)
{
return typeof(value) == "string" ? value.trim() : "";
},
/**
* Convert the value to a specific data type.
* @param {string} the data type, "Integer", "Double", "Date" or "String"
* @param {string} the value to convert.
* @type {mixed|null} the converted data value.
*/
convert : function(dataType, value)
{
if(typeof(value) == "undefined")
value = this.getValidationValue();
var string = new String(value);
switch(dataType)
{
case "Integer":
return string.toInteger();
case "Double" :
case "Float" :
return string.toDouble(this.options.DecimalChar);
case "Date":
if(typeof(value) != "string")
return value;
else
{
var value = string.toDate(this.options.DateFormat);
if(value && typeof(value.getTime) == "function")
return value.getTime();
else
return null;
}
case "String":
return string.toString();
}
return value;
},
/**
* The ControlType property comes from TBaseValidator::getClientControlClass()
* Be sure to update the TBaseValidator::$_clientClass if new cases are added.
* @return mixed control value to validate
*/
getValidationValue : function(control)
{
if(!control)
control = this.control
switch(this.options.ControlType)
{
case 'TDatePicker':
if(control.type == "text")
return this.trim($F(control));
else
{
this.observeDatePickerChanges();
return Prado.WebUI.TDatePicker.getDropDownDate(control).getTime();
}
case 'THtmlArea':
if(typeof tinyMCE != "undefined")
tinyMCE.triggerSave();
return this.trim($F(control));
case 'TRadioButton':
if(this.options.GroupName)
return this.getRadioButtonGroupValue();
default:
if(this.isListControlType())
return this.getFirstSelectedListValue();
else
return this.trim($F(control));
}
},
getRadioButtonGroupValue : function()
{
name = this.control.name;
value = "";
$A(document.getElementsByName(name)).each(function(el)
{
if(el.checked)
value = el.value;
});
return value;
},
/**
* Observe changes in the drop down list date picker, IE only.
*/
observeDatePickerChanges : function()
{
if(Prado.Browser().ie)
{
var DatePicker = Prado.WebUI.TDatePicker;
this.observeChanges(DatePicker.getDayListControl(this.control));
this.observeChanges(DatePicker.getMonthListControl(this.control));
this.observeChanges(DatePicker.getYearListControl(this.control));
}
},
/**
* Gets numeber selections and their values.
* @return object returns selected values in <tt>values</tt> property
* and number of selections in <tt>checks</tt> property.
*/
getSelectedValuesAndChecks : function(elements, initialValue)
{
var checked = 0;
var values = [];
var isSelected = this.isCheckBoxType(elements[0]) ? 'checked' : 'selected';
elements.each(function(element)
{
if(element[isSelected] && element.value != initialValue)
{
checked++;
values.push(element.value);
}
});
return {'checks' : checked, 'values' : values};
},
/**
* Gets an array of the list control item input elements, for TCheckBoxList
* checkbox inputs are returned, for TListBox HTML option elements are returned.
* @return array list control option elements.
*/
getListElements : function()
{
switch(this.options.ControlType)
{
case 'TCheckBoxList': case 'TRadioButtonList':
var elements = [];
for(var i = 0; i < this.options.TotalItems; i++)
{
var element = $(this.options.ControlToValidate+"_c"+i);
if(this.isCheckBoxType(element))
elements.push(element);
}
return elements;
case 'TListBox':
var elements = [];
var element = $(this.options.ControlToValidate);
if(element && (type = element.type.toLowerCase()))
{
if(type == "select-one" || type == "select-multiple")
elements = $A(element.options);
}
return elements;
default:
return [];
}
},
/**
* @return boolean true if element is of checkbox or radio type.
*/
isCheckBoxType : function(element)
{
if(element && element.type)
{
var type = element.type.toLowerCase();
return type == "checkbox" || type == "radio";
}
return false;
},
/**
* @return boolean true if control to validate is of some of the TListControl type.
*/
isListControlType : function()
{
var list = ['TCheckBoxList', 'TRadioButtonList', 'TListBox'];
return list.include(this.options.ControlType);
},
/**
* @return string gets the first selected list value, initial value if none found.
*/
getFirstSelectedListValue : function()
{
var initial = "";
if(typeof(this.options.InitialValue) != "undefined")
initial = this.options.InitialValue;
var elements = this.getListElements();
var selection = this.getSelectedValuesAndChecks(elements, initial);
return selection.values.length > 0 ? selection.values[0] : initial;
}
}
/**
* TRequiredFieldValidator makes the associated input control a required field.
* The input control fails validation if its value does not change from
* the <tt>InitialValue<tt> option upon losing focus.
* <code>
* options['InitialValue'] Validation fails if control input equals initial value.
* </code>
*/
Prado.WebUI.TRequiredFieldValidator = Class.extend(Prado.WebUI.TBaseValidator,
{
/**
* @return boolean true if the input value is not empty nor equal to the initial value.
*/
evaluateIsValid : function()
{
var inputType = this.control.getAttribute("type");
if(inputType == 'file')
{
return true;
}
else
{
var a = this.getValidationValue();
var b = this.trim(this.options.InitialValue);
return(a != b);
}
}
});
/**
* TCompareValidator compares the value entered by the user into an input
* control with the value entered into another input control or a constant value.
* To compare the associated input control with another input control,
* set the <tt>ControlToCompare</tt> option to the ID path
* of the control to compare with. To compare the associated input control with
* a constant value, specify the constant value to compare with by setting the
* <tt>ValueToCompare</tt> option.
*
* The <tt>DataType</tt> property is used to specify the data type
* of both comparison values. Both values are automatically converted to this data
* type before the comparison operation is performed. The following value types are supported:
* - <b>Integer</b> A 32-bit signed integer data type.
* - <b>Float</b> A double-precision floating point number data type.
* - <b>Date</b> A date data type. The format can be by the <tt>DateFormat</tt> option.
* - <b>String</b> A string data type.
*
* Use the <tt>Operator</tt> property to specify the type of comparison
* to perform. Valid operators include Equal, NotEqual, GreaterThan, GreaterThanEqual,
* LessThan and LessThanEqual.
* <code>
* options['ControlToCompare']
* options['ValueToCompare']
* options['Operator']
* options['Type']
* options['DateFormat']
* </code>
*/
Prado.WebUI.TCompareValidator = Class.extend(Prado.WebUI.TBaseValidator,
{
//_observingComparee : false,
/**
* Compares the input to another input or a given value.
*/
evaluateIsValid : function()
{
var value = this.getValidationValue();
if (value.length <= 0)
return true;
var comparee = $(this.options.ControlToCompare);
if(comparee)
var compareTo = this.getValidationValue(comparee);
else
var compareTo = this.options.ValueToCompare || "";
var isValid = this.compare(value, compareTo);
if(comparee)
{
this.updateControlCssClass(comparee, isValid);
this.observeChanges(comparee);
}
return isValid;
},
/**
* Compares two values, their values are casted to type defined
* by <tt>DataType</tt> option. False is returned if the first
* operand converts to null. Returns true if the second operand
* converts to null. The comparision is done based on the
* <tt>Operator</tt> option.
*/
compare : function(operand1, operand2)
{
var op1, op2;
if((op1 = this.convert(this.options.DataType, operand1)) == null)
return false;
if ((op2 = this.convert(this.options.DataType, operand2)) == null)
return true;
switch (this.options.Operator)
{
case "NotEqual":
return (op1 != op2);
case "GreaterThan":
return (op1 > op2);
case "GreaterThanEqual":
return (op1 >= op2);
case "LessThan":
return (op1 < op2);
case "LessThanEqual":
return (op1 <= op2);
default:
return (op1 == op2);
}
}
});
/**
* TCustomValidator performs user-defined client-side validation on an
* input component.
*
* To create a client-side validation function, add the client-side
* validation javascript function to the page template.
* The function should have the following signature:
* <code>
* <script type="text/javascript"><!--
* function ValidationFunctionName(sender, parameter)
* {
* // if(parameter == ...)
* // return true;
* // else
* // return false;
* }
* -->
* </script>
* </code>
* Use the <tt>ClientValidationFunction</tt> option
* to specify the name of the client-side validation script function associated
* with the TCustomValidator.
* <code>
* options['ClientValidationFunction'] custom validation function.
* </code>
*/
Prado.WebUI.TCustomValidator = Class.extend(Prado.WebUI.TBaseValidator,
{
/**
* Calls custom validation function.
*/
evaluateIsValid : function()
{
var value = this.getValidationValue();
var clientFunction = this.options.ClientValidationFunction;
if(typeof(clientFunction) == "string" && clientFunction.length > 0)
{
validate = clientFunction.toFunction();
return validate(this, value);
}
return true;
}
});
/**
* TRangeValidator tests whether an input value is within a specified range.
*
* TRangeValidator uses three key properties to perform its validation.
* The <tt>MinValue</tt> and <tt>MaxValue</tt> options specify the minimum
* and maximum values of the valid range. The <tt>DataType</tt> option is
* used to specify the data type of the value and the minimum and maximum range values.
* These values are converted to this data type before the validation
* operation is performed. The following value types are supported:
* - <b>Integer</b> A 32-bit signed integer data type.
* - <b>Float</b> A double-precision floating point number data type.
* - <b>Date</b> A date data type. The date format can be specified by
* setting <tt>DateFormat</tt> option, which must be recognizable
* by <tt>Date.SimpleParse</tt> javascript function.
* - <b>String</b> A string data type.
* <code>
* options['MinValue'] Minimum range value
* options['MaxValue'] Maximum range value
* options['DataType'] Value data type
* options['DateFormat'] Date format for date data type.
* </code>
*/
Prado.WebUI.TRangeValidator = Class.extend(Prado.WebUI.TBaseValidator,
{
/**
* Compares the input value with a minimum and/or maximum value.
* @return boolean true if the value is empty, returns false if conversion fails.
*/
evaluateIsValid : function()
{
var value = this.getValidationValue();
if(value.length <= 0)
return true;
if(typeof(this.options.DataType) == "undefined")
this.options.DataType = "String";
if(this.options.DataType != "StringLength")
{
var min = this.convert(this.options.DataType, this.options.MinValue || null);
var max = this.convert(this.options.DataType, this.options.MaxValue || null);
value = this.convert(this.options.DataType, value);
}
else
{
var min = this.options.MinValue || 0;
var max = this.options.MaxValue || Number.POSITIVE_INFINITY;
value = value.length;
}
if(value == null)
return false;
var valid = true;
if(min != null)
valid = valid && value >= min;
if(max != null)
valid = valid && value <= max;
return valid;
}
});
/**
* TRegularExpressionValidator validates whether the value of an associated
* input component matches the pattern specified by a regular expression.
* <code>
* options['ValidationExpression'] regular expression to match against.
* </code>
*/
Prado.WebUI.TRegularExpressionValidator = Class.extend(Prado.WebUI.TBaseValidator,
{
/**
* Compare the control input against a regular expression.
*/
evaluateIsValid : function()
{
var value = this.getValidationValue();
if (value.length <= 0)
return true;
var rx = new RegExp(this.options.ValidationExpression);
var matches = rx.exec(value);
return (matches != null && value == matches[0]);
}
});
/**
* TEmailAddressValidator validates whether the value of an associated
* input component is a valid email address.
*/
Prado.WebUI.TEmailAddressValidator = Prado.WebUI.TRegularExpressionValidator;
/**
* TListControlValidator checks the number of selection and their values
* for a TListControl that allows multiple selections.
*/
Prado.WebUI.TListControlValidator = Class.extend(Prado.WebUI.TBaseValidator,
{
/**
* @return true if the number of selections and/or their values
* match the requirements.
*/
evaluateIsValid : function()
{
var elements = this.getListElements();
if(elements && elements.length <= 0)
return true;
this.observeListElements(elements);
var selection = this.getSelectedValuesAndChecks(elements);
return this.isValidList(selection.checks, selection.values);
},
/**
* Observe list elements for IE browsers of changes
*/
observeListElements : function(elements)
{
if(Prado.Browser().ie && this.isCheckBoxType(elements[0]))
{
var validator = this;
elements.each(function(element)
{
validator.observeChanges(element);
});
}
},
/**
* Determine if the number of checked and the checked values
* satisfy the required number of checks and/or the checked values
* equal to the required values.
* @return boolean true if checked values and number of checks are satisfied.
*/
isValidList : function(checked, values)
{
var exists = true;
//check the required values
var required = this.getRequiredValues();
if(required.length > 0)
{
if(values.length < required.length)
return false;
required.each(function(requiredValue)
{
exists = exists && values.include(requiredValue);
});
}
var min = typeof(this.options.Min) == "undefined" ?
Number.NEGATIVE_INFINITY : this.options.Min;
var max = typeof(this.options.Max) == "undefined" ?
Number.POSITIVE_INFINITY : this.options.Max;
return exists && checked >= min && checked <= max;
},
/**
* @return array list of required options that must be selected.
*/
getRequiredValues : function()
{
var required = [];
if(this.options.Required && this.options.Required.length > 0)
required = this.options.Required.split(/,\s*/);
return required;
}
});
/**
* TDataTypeValidator verifies if the input data is of the type specified
* by <tt>DataType</tt> option.
* The following data types are supported:
* - <b>Integer</b> A 32-bit signed integer data type.
* - <b>Float</b> A double-precision floating point number data type.
* - <b>Date</b> A date data type.
* - <b>String</b> A string data type.
* For <b>Date</b> type, the option <tt>DateFormat</tt>
* will be used to determine how to parse the date string.
*/
Prado.WebUI.TDataTypeValidator = Class.extend(Prado.WebUI.TBaseValidator,
{
evaluateIsValid : function()
{
var value = this.getValidationValue();
if(value.length <= 0)
return true;
return this.convert(this.options.DataType, value) != null;
}
});
|