libs/cbi: add field validation handlers
[project/luci.git] / libs / cbi / htdocs / luci-static / resources / cbi.js
1 /*
2         LuCI - Lua Configuration Interface
3
4         Copyright 2008 Steven Barth <steven@midlink.org>
5         Copyright 2008-2010 Jo-Philipp Wich <xm@subsignal.org>
6
7         Licensed under the Apache License, Version 2.0 (the "License");
8         you may not use this file except in compliance with the License.
9         You may obtain a copy of the License at
10
11         http://www.apache.org/licenses/LICENSE-2.0
12 */
13
14 var cbi_d = [];
15 var cbi_t = [];
16 var cbi_c = [];
17
18 var cbi_validators = {
19
20         'integer': function(v)
21         {
22                 return (v.match(/^-?[0-9]+$/) != null);
23         },
24
25         'uinteger': function(v)
26         {
27                 return (cbi_validators.integer(v) && (v >= 0));
28         },
29
30         'ipaddr': function(v)
31         {
32                 return cbi_validators.ip4addr(v) || cbi_validators.ip6addr(v);
33         },
34
35         'ip4addr': function(v)
36         {
37                 if( v.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)(\/(\d+))?$/) )
38                 {
39                         return (RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
40                                (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
41                                (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
42                                (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
43                                (!RegExp.$5 || ((RegExp.$6 >= 0) && (RegExp.$6 <= 32)))
44                         ;
45                 }
46
47                 return false;
48         },
49
50         'ip6addr': function(v)
51         {
52                 if( v.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/) )
53                 {
54                         if( !RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)) )
55                         {
56                                 var addr = RegExp.$1;
57
58                                 if( addr == '::' )
59                                 {
60                                         return true;
61                                 }
62
63                                 if( addr.indexOf('.') > 0 )
64                                 {
65                                         var off = addr.lastIndexOf(':');
66
67                                         if( !(off && cbi_validators.ip4addr(addr.substr(off+1))) )
68                                                 return false;
69
70                                         addr = addr.substr(0, off) + ':0:0';
71                                 }
72
73                                 if( addr.indexOf('::') < 0 )
74                                 {
75                                         return (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null);
76                                 }
77
78                                 var fields = 0;
79
80                                 for( var i = 0, last = 0, comp = false; i <= addr.length; i++ )
81                                 {
82                                         if( (addr.charAt(i) == ':') || (i == addr.length) )
83                                         {
84                                                 if( (i == last) && !comp )
85                                                 {
86                                                         comp = true;
87                                                 }
88                                                 else
89                                                 {
90                                                         var f = addr.substring(last, i);
91                                                         if( !(f && f.match(/^[a-fA-F0-9]{1,4}$/)) )
92                                                                 return false;
93                                                 }
94
95                                                 fields++;
96                                                 last = i + 1;
97                                         }                               
98                                 }
99
100                                 return (fields == 8);
101                         }
102                 }
103
104                 return false;
105         },
106
107         'port': function(v)
108         {
109                 return cbi_validators.integer(v) && (v >= 0) && (v <= 65535);
110         },
111
112         'portrange': function(v)
113         {
114                 if( v.match(/^(\d+)-(\d+)$/) )
115                 {
116                         var p1 = RegExp.$1;
117                         var p2 = RegExp.$2;
118
119                         return cbi_validators.port(p1) &&
120                                cbi_validators.port(p2) &&
121                                (parseInt(p1) <= parseInt(p2))
122                         ;
123                 }
124                 else
125                 {
126                         return cbi_validators.port(v);
127                 }
128         },
129
130         'macaddr': function(v)
131         {
132                 return (v.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null);
133         },
134
135         'host': function(v)
136         {
137                 return cbi_validators.hostname(v) || cbi_validators.ipaddr(v);
138         },
139
140         'hostname': function(v)
141         {
142                 return (v.match(/^[a-zA-Z_][a-zA-Z0-9_\-.]*$/) != null);
143         },
144
145         'wpakey': function(v)
146         {
147                 if( v.length == 64 )
148                         return (v.match(/^[a-fA-F0-9]{64}$/) != null);
149                 else
150                         return (v.length >= 8) && (v.length <= 63);
151         },
152
153         'wepkey': function(v)
154         {
155                 if( v.substr(0,2) == 's:' )
156                         v = v.substr(2);
157
158                 if( (v.length == 10) || (v.length == 26) )
159                         return (v.match(/^[a-fA-F0-9]{10,26}$/) != null);
160                 else
161                         return (v.length == 5) || (v.length == 13);
162         },
163
164 };
165
166
167 function cbi_d_add(field, dep, next) {
168         var obj = document.getElementById(field);
169         if (obj) {
170                 var entry
171                 for (var i=0; i<cbi_d.length; i++) {
172                         if (cbi_d[i].id == field) {
173                                 entry = cbi_d[i];
174                                 break;
175                         }
176                 }
177                 if (!entry) {
178                         entry = {
179                                 "node": obj,
180                                 "id": field,
181                                 "parent": obj.parentNode.id,
182                                 "next": next,
183                                 "deps": []
184                         };
185                         cbi_d.unshift(entry);
186                 }
187                 entry.deps.push(dep)
188         }
189 }
190
191 function cbi_d_checkvalue(target, ref) {
192         var t = document.getElementById(target);
193         var value;
194
195         if (!t) {
196                 var tl = document.getElementsByName(target);
197
198                 if( tl.length > 0 && tl[0].type == 'radio' )
199                         for( var i = 0; i < tl.length; i++ )
200                                 if( tl[i].checked ) {
201                                         value = tl[i].value;
202                                         break;
203                                 }
204
205                 value = value ? value : "";
206         } else if (!t.value) {
207                 value = "";
208         } else {
209                 value = t.value;
210
211                 if (t.type == "checkbox") {
212                         value = t.checked ? value : "";
213                 }
214         }
215
216         return (value == ref)
217 }
218
219 function cbi_d_check(deps) {
220         var reverse;
221         var def = false;
222         for (var i=0; i<deps.length; i++) {
223                 var istat = true;
224                 reverse = false;
225                 for (var j in deps[i]) {
226                         if (j == "!reverse") {
227                                 reverse = true;
228                         } else if (j == "!default") {
229                                 def = true;
230                                 istat = false;
231                         } else {
232                                 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
233                         }
234                 }
235                 if (istat) {
236                         return !reverse;
237                 }
238         }
239         return def;
240 }
241
242 function cbi_d_update() {
243         var state = false;
244         for (var i=0; i<cbi_d.length; i++) {
245                 var entry = cbi_d[i];
246                 var next  = document.getElementById(entry.next)
247                 var node  = document.getElementById(entry.id)
248                 var parent = document.getElementById(entry.parent)
249
250                 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
251                         node.parentNode.removeChild(node);
252                         state = true;
253                         if( entry.parent )
254                                 cbi_c[entry.parent]--;
255                 } else if ((!node || !node.parentNode) && cbi_d_check(entry.deps)) {
256                         if (!next) {
257                                 parent.appendChild(entry.node);
258                         } else {
259                                 next.parentNode.insertBefore(entry.node, next);
260                         }
261                         state = true;
262                         if( entry.parent )
263                                 cbi_c[entry.parent]++;
264                 }
265         }
266
267         if (entry.parent) {
268                 cbi_t_update();
269         }
270
271         if (state) {
272                 cbi_d_update();
273         }
274 }
275
276 function cbi_bind(obj, type, callback, mode) {
277         if (typeof mode == "undefined") {
278                 mode = false;
279         }
280         if (!obj.addEventListener) {
281                 ieCallback = function(){
282                         var e = window.event;
283                         if (!e.target && e.srcElement) {
284                                 e.target = e.srcElement;
285                         };
286                         e.target['_eCB' + type + callback] = callback;
287                         e.target['_eCB' + type + callback](e);
288                         e.target['_eCB' + type + callback] = null;
289                 };
290                 obj.attachEvent('on' + type, ieCallback);
291         } else {
292                 obj.addEventListener(type, callback, mode);
293         }
294         return obj;
295 }
296
297 function cbi_combobox(id, values, def, man) {
298         var selid = "cbi.combobox." + id;
299         if (document.getElementById(selid)) {
300                 return
301         }
302
303         var obj = document.getElementById(id)
304         var sel = document.createElement("select");
305         sel.id = selid;
306         sel.className = 'cbi-input-select';
307         if (obj.nextSibling) {
308                 obj.parentNode.insertBefore(sel, obj.nextSibling);
309         } else {
310                 obj.parentNode.appendChild(sel);
311         }
312
313         if (!values[obj.value]) {
314                 if (obj.value == "") {
315                         var optdef = document.createElement("option");
316                         optdef.value = "";
317                         optdef.appendChild(document.createTextNode(def));
318                         sel.appendChild(optdef);
319                 } else {
320                         var opt = document.createElement("option");
321                         opt.value = obj.value;
322                         opt.selected = "selected";
323                         opt.appendChild(document.createTextNode(obj.value));
324                         sel.appendChild(opt);
325                 }
326         }
327
328         for (var i in values) {
329                 var opt = document.createElement("option");
330                 opt.value = i;
331
332                 if (obj.value == i) {
333                         opt.selected = "selected";
334                 }
335
336                 opt.appendChild(document.createTextNode(values[i]));
337                 sel.appendChild(opt);
338         }
339
340         var optman = document.createElement("option");
341         optman.value = "";
342         optman.appendChild(document.createTextNode(man));
343         sel.appendChild(optman);
344
345         obj.style.display = "none";
346
347         cbi_bind(sel, "change", function() {
348                 if (sel.selectedIndex == sel.options.length - 1) {
349                         obj.style.display = "inline";
350                         sel.parentNode.removeChild(sel);
351                         obj.focus();
352                 } else {
353                         obj.value = sel.options[sel.selectedIndex].value;
354                 }
355
356                 try {
357                         cbi_d_update();
358                 } catch (e) {
359                         //Do nothing
360                 }
361         })
362 }
363
364 function cbi_combobox_init(id, values, def, man) {
365         var obj = document.getElementById(id);
366         cbi_bind(obj, "blur", function() {
367                 cbi_combobox(id, values, def, man)
368         });
369         cbi_combobox(id, values, def, man);
370 }
371
372 function cbi_filebrowser(id, url, defpath) {
373         var field   = document.getElementById(id);
374         var browser = window.open(
375                 url + ( field.value || defpath || '' ) + '?field=' + id,
376                 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
377         );
378
379         browser.focus();
380 }
381
382 //Hijacks the CBI form to send via XHR (requires Prototype)
383 function cbi_hijack_forms(layer, win, fail, load) {
384         var forms = layer.getElementsByTagName('form');
385         for (var i=0; i<forms.length; i++) {
386                 $(forms[i]).observe('submit', function(event) {
387                         // Prevent the form from also submitting the regular way
388                         event.stop();
389
390                         // Submit via XHR
391                         event.element().request({
392                                 onSuccess: win,
393                                 onFailure: fail
394                         });
395
396                         if (load) {
397                                 load();
398                         }
399                 });
400         }
401 }
402
403
404 function cbi_t_add(section, tab) {
405         var t = document.getElementById('tab.' + section + '.' + tab);
406         var c = document.getElementById('container.' + section + '.' + tab);
407
408         if( t && c ) {
409                 cbi_t[section] = (cbi_t[section] || [ ]);
410                 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
411         }
412 }
413
414 function cbi_t_switch(section, tab) {
415         if( cbi_t[section] && cbi_t[section][tab] ) {
416                 var o = cbi_t[section][tab];
417                 var h = document.getElementById('tab.' + section);
418                 for( var tid in cbi_t[section] ) {
419                         var o2 = cbi_t[section][tid];
420                         if( o.tab.id != o2.tab.id ) {
421                                 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
422                                 o2.container.style.display = 'none';
423                         }
424                         else {
425                                 if(h) h.value = tab;
426                                 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
427                                 o2.container.style.display = 'block';
428                         }
429                 }
430         }
431         return false
432 }
433
434 function cbi_t_update() {
435         for( var sid in cbi_t )
436                 for( var tid in cbi_t[sid] )
437                         if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
438                                 cbi_t[sid][tid].tab.style.display = 'none';
439                         }
440                         else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
441                                 cbi_t[sid][tid].tab.style.display = '';
442
443                                 var t = cbi_t[sid][tid].tab;
444                                 window.setTimeout(function() { t.className = t.className.replace(/ cbi-tab-highlighted/g, '') }, 750);
445                                 cbi_t[sid][tid].tab.className += ' cbi-tab-highlighted';
446                         }
447 }
448
449
450 function cbi_validate_disable_form(form, onoff)
451 {
452         for( var i = 0; i < form.elements.length; i++ )
453         {
454                 if( form.elements[i].type == 'submit' )
455                 {
456                         form.elements[i].disabled = onoff;
457                         break;
458                 }
459         }
460 }
461
462 function cbi_validate_field(type, optional, field)
463 {
464         var vldcb = cbi_validators[type];
465         if( vldcb )
466         {
467                 var value = (field.options) ? field.options[field.options.selectedIndex].value : field.value;
468
469                 if( ((value.length == 0) && optional) || vldcb(value) )
470                 {
471                         // OK
472                         field.className = field.className.replace(/ cbi-input-invalid/g, '');
473                         cbi_validate_disable_form(field.form, false);
474                 }
475                 else
476                 {
477                         // Invalid
478                         field.className += ' cbi-input-invalid';
479                         cbi_validate_disable_form(field.form, true);
480                 }
481         }
482         else
483         {
484                 // OK
485                 field.className = field.className.replace(/ cbi-input-invalid/g, '');
486                 cbi_validate_disable_form(field.form, false);
487         }
488 }
489