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