2006-02-15 Igor Zelmanovich <igorz@mainsoft.com>
[mono.git] / mcs / class / System.Web / resources / WebUIValidation_2.0.js
1 /*
2  * WebUIValidation.js
3  *
4  * Authors:
5  *   Chris Toshok (toshok@ximian.com)
6  *
7  * (c) 2005 Novell, Inc. (http://www.novell.com)
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining
10  * a copy of this software and associated documentation files (the
11  * "Software"), to deal in the Software without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27  */
28
29 var have_validation_summaries = false;
30
31 function SetValidatorContext (currForm)
32 {
33         if (currForm.Page_Validators && (Page_Validators != currForm.Page_Validators)) {
34                 Page_Validators = currForm.Page_Validators;
35                 Page_ValidationSummaries = currForm.Page_ValidationSummaries;
36                 ValidatorOnLoad ();
37         }
38 }
39
40 function ValidatorOnLoad ()
41 {
42         if (typeof (Page_ValidationSummaries) != 'undefined' && Page_ValidationSummaries != null) {
43                 have_validation_summaries = true;
44                   for (var v = 0; v < Page_ValidationSummaries.length; v++) {
45                     var vs = Page_ValidationSummaries [v];
46                     if (vs.getAttribute ("validationgroup") == null)
47                             vs.setAttribute ("validationgroup", "");
48             }
49         }
50
51         for (var v = 0; v < Page_Validators.length; v++) {
52                 var vo = Page_Validators [v];
53
54                 if (vo.getAttribute ("isvalid") == null)
55                         vo.setAttribute ("isvalid", "true");
56
57                 if (vo.getAttribute ("enabled") == null)
58                         vo.setAttribute ("enabled", "true");
59
60                 if (vo.getAttribute ("validationgroup") == null)
61                         vo.setAttribute ("validationgroup", "");
62         }
63
64         Page_ValidationActive = true;
65 }
66
67 var validation_result = true;
68
69 function ValidationSummaryOnSubmit (group)
70 {
71         /* handle validation summaries here */
72         if (validation_result == false && have_validation_summaries) {
73
74           for (var vi = 0; vi < Page_ValidationSummaries.length; vi++) {
75                         var vs = Page_ValidationSummaries[vi];
76                     
77                     if(IsValidationGroupMatch(vs, group)) {
78
79                             var header = vs.getAttribute ("headertext");
80                             if (header == null)
81                                     header = "";
82
83                             attr = vs.getAttribute ("showsummary");
84                             if (attr == null || attr.toLowerCase() == "true") {
85                                     var displaymode = vs.getAttribute ("displaymode");
86                                     if (displaymode == null) displaymode = "Bulleted";
87
88                                     var html = "";
89
90                                     if (displaymode == "List") {
91                                             list_pre = "";
92                                             list_post = "";
93                                             item_pre = "";
94                                             item_post = "<br>";
95                                     }
96                                     else if (displaymode == "SingleParagraph") {
97                                             list_pre = "";
98                                             list_post = "<br>";
99                                             item_pre = "";
100                                             item_post = " ";
101                                     }
102                                     else {
103                                             list_pre = "<ul>";
104                                             list_post = "</ul>";
105                                             item_pre = "\n<li>";
106                                             item_post = "</li>";
107                                     }
108
109                                     html += header;
110                                     html += list_pre;
111                                                 for (var v = 0; v < Page_Validators.length; v++) {
112                                       var vo = Page_Validators [v];
113
114                                             if (vo.getAttribute ("isvalid").toLowerCase() == "false") {
115                                                     var text = ValidatorGetErrorMessage (vo);
116                                                     if (text != null && text != "") {
117                                                             html += item_pre + text + item_post;
118                                                     }
119                                             }
120                                     }
121                                     html += list_post;
122
123                                     vs.innerHTML = html;
124                                     vs.style.display = "block";
125                             }
126
127                             attr = vs.getAttribute ("showmessagebox");
128                             if (attr != null && attr.toLowerCase() == "true") {
129                                     var v_contents = "";
130
131                                                 for (var v = 0; v < Page_Validators.length; v++) {
132                                       var vo = Page_Validators [v];
133
134                                             if (vo.getAttribute ("isvalid").toLowerCase() == "false") {
135                                                     var text = ValidatorGetErrorMessage (vo);
136                                                     if (text != null && text != "") {
137                                                             v_contents += "-" + text + "\n";
138                                                     }
139                                             }
140                                     }
141
142                                     var alert_header = header;
143                                     if (alert_header != "")
144                                             alert_header += "\n";
145                                     summary_contents = alert_header + v_contents;
146                                     alert (summary_contents);
147                             }
148                         }
149                 }
150         }
151 }
152
153 function ValidatorCommonOnSubmit ()
154 {
155         rv = validation_result;
156         validation_result = true;
157         return rv;
158 }
159
160 function ValidatorGetValue (controlname)
161 {
162         var el = GetElement (controlname);
163
164         /* if the element has a 'value' attribute, return it */
165         if (typeof (el.value) != 'undefined' && el.value != null) {
166                 return el.value;
167         }
168
169         /* if it's a select, loop over the options looking for the
170          * selected one. */
171         if (typeof (el.selectedIndex) != 'undefined') {
172                 return el.options[el.selectedIndex].value;
173         }
174 }
175
176 function ValidatorTrim (s)
177 {
178         s = s.replace (/^\s+/g, "");
179         s = s.replace (/\s+$/g, "");
180
181         return s;
182 }
183
184 function Page_ClientValidate(group)
185 {
186         validation_result = true;
187
188         /* clear out the existing text from all our summaries */
189         if (have_validation_summaries) {
190           for (var vi = 0; vi < Page_ValidationSummaries.length; vi++) {
191                         var vs = Page_ValidationSummaries[vi];
192                         vs.style.display = "none";
193                         vs.innerHTML = "";
194                 }
195         }
196         
197         var invalidControlHasBeenFocused = false;
198         for (var v = 0; v < Page_Validators.length; v++) {
199                 var vo = Page_Validators [v];
200                 var evalfunc = this[vo.getAttribute ("evaluationfunction")];
201                 var result = false;
202
203                 if (vo.getAttribute ("enabled").toLowerCase() == "false" || !IsValidationGroupMatch(vo, group)) {
204                         result = true;
205                         ValidatorSucceeded (vo);
206                 }
207                 else {
208                         result = evalfunc (vo);
209                 }
210
211                 if (!result) {
212                         validation_result = false;
213                         if (!invalidControlHasBeenFocused && typeof(vo.focusOnError) == "string" && vo.focusOnError == "t") {
214                                 invalidControlHasBeenFocused = ValidatorSetFocus(vo);
215                         }
216                 }
217                 
218                 vo.setAttribute("isvalid", result ? "true" : "false");
219         }
220     ValidationSummaryOnSubmit(group);
221         return validation_result;
222 }
223
224 function IsValidationGroupMatch(vo, group) {
225     var valGroup = vo.getAttribute ("validationgroup");
226     if ((typeof(group) == "undefined") || (group == null)) {
227         return (valGroup == "");
228     }
229     return (valGroup == group);
230 }
231
232 function ValidatorSetFocus(val) {
233     var ctrl = document.getElementById(val.getAttribute ("controltovalidate"));
234         if ((typeof(ctrl) != "undefined") && (ctrl != null) &&
235                 ((ctrl.tagName.toLowerCase() != "input") || (ctrl.type.toLowerCase() != "hidden")) &&
236                 (typeof(ctrl.disabled) == "undefined" || ctrl.disabled == null || ctrl.disabled == false) &&
237                 (typeof(ctrl.visible) == "undefined" || ctrl.visible == null || ctrl.visible != false) &&
238                 (IsInVisibleContainer(ctrl))) {
239                 if (ctrl.tagName.toLowerCase() == "table") {
240                         var inputElements = ctrl.getElementsByTagName("input");
241                         var lastInputElement  = inputElements[inputElements.length -1];
242                         if (lastInputElement != null) {
243                                 ctrl = lastInputElement;
244                         }
245                 }
246                 if (typeof(ctrl.focus) != "undefined" && ctrl.focus != null) {
247                         ctrl.focus();
248                         return true;
249                 }
250     }
251     return false;
252 }
253
254 function IsInVisibleContainer(ctrl) {
255         if (typeof(ctrl.style) != "undefined" && 
256                 ((typeof(ctrl.style.display) != "undefined" &&  ctrl.style.display == "none") ||
257                 (typeof(ctrl.style.visibility) != "undefined" && ctrl.style.visibility == "hidden"))) {
258                 return false;
259         }
260         else if (typeof(ctrl.parentNode) != "undefined" && ctrl.parentNode != null && ctrl.parentNode != ctrl) {
261                 return IsInVisibleContainer(ctrl.parentNode);
262         }
263         return true;
264 }
265
266 /*******************/
267 /* type converters */
268
269 function ToInteger (s, validator)
270 {
271         if ((v = parseInt(s, 10)) != s - 0)
272                 return null;
273         else
274                 return v;
275 }
276
277 function ToString (s, validator)
278 {
279         return s;
280 }
281
282 function ToDouble (s, validator)
283 {
284         if ((v = parseFloat(s)) != s - 0)
285                 return null;
286         else
287                 return v;
288 }
289
290 function ToDate (s, validator)
291 {
292     var m, day, month, year;
293     var yearFirstExp = new RegExp("^\\s*((\\d{4})|(\\d{2}))([-/]|\\. ?)(\\d{1,2})\\4(\\d{1,2})\\s*$");
294     m = s.match(yearFirstExp);
295     if (m != null && (m[2].length == 4 || validator.dateorder == "ymd")) {
296         day = m[6];
297         month = m[5];
298         year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10), validator.cutoffyear)
299     }
300     else {
301         if (validator.dateorder == "ymd") return null;
302         var yearLastExp = new RegExp("^\\s*(\\d{1,2})([-/]|\\. ?)(\\d{1,2})\\2((\\d{4})|(\\d{2}))\\s*$");
303         m = s.match(yearLastExp);
304         if (m == null) return null;
305         if (validator.dateorder == "mdy") {
306             day = m[3];
307             month = m[1];
308         }
309         else {
310             day = m[1];
311             month = m[3];
312         }
313         year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10), validator.cutoffyear)
314     }
315     month -= 1;
316     var date = new Date(year, month, day);
317     return (typeof(date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null;
318 }
319
320 function ToCurrency (s, validator)
321 {
322         var hasDigits = (validator.digits > 0);
323         var beginGroupSize, subsequentGroupSize;
324         var groupSizeNum = parseInt(validator.groupsize, 10);
325         if (!isNaN(groupSizeNum) && groupSizeNum > 0) {
326                 beginGroupSize = "{1," + groupSizeNum + "}";
327                 subsequentGroupSize = "{" + groupSizeNum + "}";
328         }
329         else {
330                 beginGroupSize = subsequentGroupSize = "+";
331         }
332         var exp = new RegExp("^\\s*([-\\+])?((\\d" + beginGroupSize + "(\\" + validator.groupchar + "\\d" + subsequentGroupSize + ")+)|\\d*)"
333                                         + (hasDigits ? "\\" + validator.decimalchar + "?(\\d{0," + validator.digits + "})" : "")
334                                         + "\\s*$");
335         var m = s.match(exp);
336         if (m == null)
337                 return null;
338         if (m[2].length == 0 && hasDigits && m[5].length == 0)
339                 return null;
340         var cleanInput = (m[1] != null ? m[1] : "") + m[2].replace(new RegExp("(\\" + validator.groupchar + ")", "g"), "") + ((hasDigits && m[5].length > 0) ? "." + m[5] : "");
341         var num = parseFloat(cleanInput);
342         return (isNaN(num) ? null : num);
343 }
344
345 function GetFullYear(year, maxYear)
346 {
347     var twoDigitMaxYear = maxYear % 100;
348     var centure = maxYear - twoDigitMaxYear;
349     return ((year > twoDigitMaxYear) ? (centure - 100 + year) : (centure + year));
350 }
351
352 /*******************/
353 /* validators     */
354
355 function CompareValidatorEvaluateIsValid (validator)
356 {
357         var ControlToCompare = validator.getAttribute ("controltocompare");
358         var ValueToCompare = validator.getAttribute ("valuetocompare");
359         var Operator = validator.getAttribute ("operator").toLowerCase();
360         var ControlToValidate = validator.getAttribute ("controltovalidate");
361         var DataType = validator.getAttribute ("datatype");
362
363         var ctrl_value = ValidatorTrim (ValidatorGetValue (ControlToValidate));
364         if (ctrl_value == "") {
365                 ValidatorSucceeded (validator);
366                 return true;
367         }
368         var compare = (ControlToCompare != null && ControlToCompare != "") ? ValidatorTrim (ValidatorGetValue (ControlToCompare)) : ValueToCompare;
369
370         var left = Convert (ctrl_value, DataType, validator);
371         if (left == null) {
372                 ValidatorFailed (validator);
373                 return false;
374         }
375       
376         var right = compare != null ? Convert (compare, DataType, validator) : null;
377         if (right == null) {
378                 ValidatorSucceeded (validator);
379                  return true;
380         }
381
382         var result = false;
383    
384         if (Operator == "equal") {
385                 result = (left == right);
386         }
387         else if (Operator == "notequal") {
388                 result = (left != right);
389         }
390         else if (Operator == "lessthan") {
391                 result = (left < right);
392         }
393         else if (Operator == "lessthanequal") {
394                 result = (left <= right);
395         }
396         else if (Operator == "greaterthan") {
397                 result = (left > right);
398         }
399         else if (Operator == "greaterthanequal") {
400                 result = (left >= right);
401         }
402
403         if (result == false) {
404                 ValidatorFailed (validator);
405                 return false;
406         }
407         else {
408                 ValidatorSucceeded (validator);
409                 return true;
410         }
411 }
412
413 function RangeValidatorEvaluateIsValid (validator)
414 {
415         var ControlToValidate = validator.getAttribute ("controltovalidate");
416         var DataType = validator.getAttribute ("datatype");
417
418         var ctrl_value = ValidatorTrim (ValidatorGetValue (ControlToValidate));
419
420         if (ctrl_value == "") {
421                 ValidatorSucceeded (validator);
422                 return true;
423         }
424
425         var MinimumValue = Convert (validator.getAttribute ("minimumvalue"), DataType, validator);
426         var MaximumValue = Convert (validator.getAttribute ("maximumvalue"), DataType, validator);
427         var val = Convert (ctrl_value, DataType, validator);
428         if (val == null || val <= MinimumValue || val >= MaximumValue) {
429                 ValidatorFailed (validator);
430                 return false;
431         }
432         else {
433                 ValidatorSucceeded (validator);
434                 return true;
435         }
436 }
437
438 function RegularExpressionValidatorEvaluateIsValid (validator)
439 {
440         var ValidationExpression = validator.getAttribute ("validationexpression");
441         var ControlToValidate = validator.getAttribute ("controltovalidate");
442
443         var ctrl_value = ValidatorTrim (ValidatorGetValue (ControlToValidate));
444
445         if (ctrl_value == "") {
446                 ValidatorSucceeded (validator);
447                 return true;
448         }
449
450         var r = new RegExp (ValidationExpression);
451         match = r.exec (ctrl_value);
452         if (match == null || match[0] == "") {
453                 ValidatorFailed (validator);
454                 return false;
455         }
456         else {
457                 ValidatorSucceeded (validator);
458                 return true;
459         }
460 }
461
462 function RequiredFieldValidatorEvaluateIsValid (validator)
463 {
464         var InitialValue = validator.getAttribute ("initialvalue");
465         var ControlToValidate = validator.getAttribute ("controltovalidate");
466
467         var ctrl_value = ValidatorTrim (ValidatorGetValue (ControlToValidate));
468
469         if (ctrl_value == ValidatorTrim (InitialValue)) {
470                 ValidatorFailed (validator);
471                 return false;
472         }
473         else {
474                 ValidatorSucceeded (validator);
475                 return true;
476         }
477 }
478
479 function CustomValidatorEvaluateIsValid (validator)
480 {
481         var InitialValue = validator.getAttribute ("initialvalue");
482         var ControlToValidate = validator.getAttribute ("controltovalidate");
483
484         if (!ControlToValidate) {
485                 ValidatorSucceeded (validator);
486                 return true;
487         }
488
489         var evaluationfunc = validator.getAttribute ("clientvalidationfunction");
490
491         var ctrl_value = ValidatorTrim (ValidatorGetValue (ControlToValidate));
492         
493     if ((ctrl_value.length == 0) && ((typeof(validator.validateemptytext) != "string") || (validator.validateemptytext != "true"))) {
494                 ValidatorSucceeded (validator);
495                 return true;
496         }
497
498         var result = true;
499
500         if (evaluationfunc && evaluationfunc != "") {
501                 args = {Value:ctrl_value, IsValid:true};
502                 eval (evaluationfunc + "(validator, args)");
503                 result = args.IsValid;
504         }
505
506         if (result) {
507                 ValidatorSucceeded (validator);
508                 return true;
509         }
510         else {
511                 ValidatorFailed (validator);
512                 return false;
513         }
514 }
515
516 /*********************/
517 /* utility functions */
518
519 function Convert (s, ty, validator)
520 {
521         var cvt = this ["To" + ty];
522         if (typeof (cvt) == 'function')
523                 return cvt (s, validator);
524         else
525                 return null;
526 }
527
528 function ValidatorUpdateDisplay (v, valid)
529 {
530         var display = v.getAttribute ("display");
531
532         /* for validators that aren't displayed, do nothing */
533         if (display == "None") {
534                 return;
535         }
536
537         v.style.visibility = (valid ? "hidden" : "visible");
538         if (display == "Dynamic") {
539                 v.style.display = (valid ? "none" : "inline");
540         }
541 }
542
543 function ValidatorGetErrorMessage (v)
544 {
545         var text = v.getAttribute ("errormessage");
546         if (text == null || text == "")
547                 text = v.getAttribute ("text"); 
548         if (text == null)
549                 text = "";
550         return text;
551 }
552
553 function ValidatorGetText (v)
554 {
555         var text = v.getAttribute ("text");     
556         if (text == null || text == "")
557                 text = v.getAttribute ("errormessage");
558         if (text == null)
559                 text = "";
560         return text;
561 }
562
563 function ValidatorFailed (v)
564 {
565         ValidatorUpdateDisplay (v, false);
566 }
567
568 function ValidatorSucceeded (v)
569 {
570         ValidatorUpdateDisplay (v, true);
571 }
572
573 function GetElement(id)
574 {
575         var x = document.getElementById ? document.getElementById (id) :
576                                           ((document.all) ? document.all [id] : null);
577         return x;
578 }