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