libs/web: fix ip6addr js validation, fixes for live validation
[project/luci.git] / libs / web / 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 var colons = 0;
76 var fill = '0';
77
78 for( var i = 0; i < addr.length; i++ )
79 if( addr.charAt(i) == ':' )
80 colons++;
81
82 if( colons > 7 )
83 return false;
84
85 for( var i = 0; i < (7 - colons); i++ )
86 fill += ':0';
87
88 addr = addr.replace(/::/, ':' + fill + ':');
89 }
90
91 return (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null);
92 }
93 }
94
95 return false;
96 },
97
98 'port': function(v)
99 {
100 return cbi_validators.integer(v) && (v >= 0) && (v <= 65535);
101 },
102
103 'portrange': function(v)
104 {
105 if( v.match(/^(\d+)-(\d+)$/) )
106 {
107 var p1 = RegExp.$1;
108 var p2 = RegExp.$2;
109
110 return cbi_validators.port(p1) &&
111 cbi_validators.port(p2) &&
112 (parseInt(p1) <= parseInt(p2))
113 ;
114 }
115 else
116 {
117 return cbi_validators.port(v);
118 }
119 },
120
121 'macaddr': function(v)
122 {
123 return (v.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null);
124 },
125
126 'host': function(v)
127 {
128 return cbi_validators.hostname(v) || cbi_validators.ipaddr(v);
129 },
130
131 'hostname': function(v)
132 {
133 return (v.match(/^[a-zA-Z_][a-zA-Z0-9_\-.]*$/) != null);
134 },
135
136 'wpakey': function(v)
137 {
138 if( v.length == 64 )
139 return (v.match(/^[a-fA-F0-9]{64}$/) != null);
140 else
141 return (v.length >= 8) && (v.length <= 63);
142 },
143
144 'wepkey': function(v)
145 {
146 if( v.substr(0,2) == 's:' )
147 v = v.substr(2);
148
149 if( (v.length == 10) || (v.length == 26) )
150 return (v.match(/^[a-fA-F0-9]{10,26}$/) != null);
151 else
152 return (v.length == 5) || (v.length == 13);
153 },
154
155 };
156
157
158 function cbi_d_add(field, dep, next) {
159 var obj = document.getElementById(field);
160 if (obj) {
161 var entry
162 for (var i=0; i<cbi_d.length; i++) {
163 if (cbi_d[i].id == field) {
164 entry = cbi_d[i];
165 break;
166 }
167 }
168 if (!entry) {
169 entry = {
170 "node": obj,
171 "id": field,
172 "parent": obj.parentNode.id,
173 "next": next,
174 "deps": []
175 };
176 cbi_d.unshift(entry);
177 }
178 entry.deps.push(dep)
179 }
180 }
181
182 function cbi_d_checkvalue(target, ref) {
183 var t = document.getElementById(target);
184 var value;
185
186 if (!t) {
187 var tl = document.getElementsByName(target);
188
189 if( tl.length > 0 && tl[0].type == 'radio' )
190 for( var i = 0; i < tl.length; i++ )
191 if( tl[i].checked ) {
192 value = tl[i].value;
193 break;
194 }
195
196 value = value ? value : "";
197 } else if (!t.value) {
198 value = "";
199 } else {
200 value = t.value;
201
202 if (t.type == "checkbox") {
203 value = t.checked ? value : "";
204 }
205 }
206
207 return (value == ref)
208 }
209
210 function cbi_d_check(deps) {
211 var reverse;
212 var def = false;
213 for (var i=0; i<deps.length; i++) {
214 var istat = true;
215 reverse = false;
216 for (var j in deps[i]) {
217 if (j == "!reverse") {
218 reverse = true;
219 } else if (j == "!default") {
220 def = true;
221 istat = false;
222 } else {
223 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
224 }
225 }
226 if (istat) {
227 return !reverse;
228 }
229 }
230 return def;
231 }
232
233 function cbi_d_update() {
234 var state = false;
235 for (var i=0; i<cbi_d.length; i++) {
236 var entry = cbi_d[i];
237 var next = document.getElementById(entry.next)
238 var node = document.getElementById(entry.id)
239 var parent = document.getElementById(entry.parent)
240
241 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
242 node.parentNode.removeChild(node);
243 state = true;
244 if( entry.parent )
245 cbi_c[entry.parent]--;
246 } else if ((!node || !node.parentNode) && cbi_d_check(entry.deps)) {
247 if (!next) {
248 parent.appendChild(entry.node);
249 } else {
250 next.parentNode.insertBefore(entry.node, next);
251 }
252 state = true;
253 if( entry.parent )
254 cbi_c[entry.parent]++;
255 }
256 }
257
258 if (entry && entry.parent) {
259 cbi_t_update();
260 }
261
262 if (state) {
263 cbi_d_update();
264 }
265 }
266
267 function cbi_bind(obj, type, callback, mode) {
268 if (typeof mode == "undefined") {
269 mode = false;
270 }
271 if (!obj.addEventListener) {
272 ieCallback = function(){
273 var e = window.event;
274 if (!e.target && e.srcElement) {
275 e.target = e.srcElement;
276 };
277 e.target['_eCB' + type + callback] = callback;
278 e.target['_eCB' + type + callback](e);
279 e.target['_eCB' + type + callback] = null;
280 };
281 obj.attachEvent('on' + type, ieCallback);
282 } else {
283 obj.addEventListener(type, callback, mode);
284 }
285 return obj;
286 }
287
288 function cbi_combobox(id, values, def, man) {
289 var selid = "cbi.combobox." + id;
290 if (document.getElementById(selid)) {
291 return
292 }
293
294 var obj = document.getElementById(id)
295 var sel = document.createElement("select");
296 sel.id = selid;
297 sel.className = 'cbi-input-select';
298 if (obj.className && obj.className.match(/cbi-input-invalid/)) {
299 sel.className += ' cbi-input-invalid';
300 }
301 if (obj.nextSibling) {
302 obj.parentNode.insertBefore(sel, obj.nextSibling);
303 } else {
304 obj.parentNode.appendChild(sel);
305 }
306
307 if (!values[obj.value]) {
308 if (obj.value == "") {
309 var optdef = document.createElement("option");
310 optdef.value = "";
311 optdef.appendChild(document.createTextNode(def));
312 sel.appendChild(optdef);
313 } else {
314 var opt = document.createElement("option");
315 opt.value = obj.value;
316 opt.selected = "selected";
317 opt.appendChild(document.createTextNode(obj.value));
318 sel.appendChild(opt);
319 }
320 }
321
322 for (var i in values) {
323 var opt = document.createElement("option");
324 opt.value = i;
325
326 if (obj.value == i) {
327 opt.selected = "selected";
328 }
329
330 opt.appendChild(document.createTextNode(values[i]));
331 sel.appendChild(opt);
332 }
333
334 var optman = document.createElement("option");
335 optman.value = "";
336 optman.appendChild(document.createTextNode(man));
337 sel.appendChild(optman);
338
339 obj.style.display = "none";
340
341 cbi_bind(sel, "change", function() {
342 if (sel.selectedIndex == sel.options.length - 1) {
343 obj.style.display = "inline";
344 sel.parentNode.removeChild(sel);
345 obj.focus();
346 } else {
347 obj.value = sel.options[sel.selectedIndex].value;
348 sel.className = (!obj.validate || obj.validate())
349 ? 'cbi-input-select' : 'cbi-input-select cbi-input-invalid';
350 }
351
352 try {
353 cbi_d_update();
354 } catch (e) {
355 //Do nothing
356 }
357 })
358 }
359
360 function cbi_combobox_init(id, values, def, man) {
361 var obj = document.getElementById(id);
362 cbi_bind(obj, "blur", function() {
363 cbi_combobox(id, values, def, man)
364 });
365 cbi_combobox(id, values, def, man);
366 }
367
368 function cbi_filebrowser(id, url, defpath) {
369 var field = document.getElementById(id);
370 var browser = window.open(
371 url + ( field.value || defpath || '' ) + '?field=' + id,
372 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
373 );
374
375 browser.focus();
376 }
377
378 //Hijacks the CBI form to send via XHR (requires Prototype)
379 function cbi_hijack_forms(layer, win, fail, load) {
380 var forms = layer.getElementsByTagName('form');
381 for (var i=0; i<forms.length; i++) {
382 $(forms[i]).observe('submit', function(event) {
383 // Prevent the form from also submitting the regular way
384 event.stop();
385
386 // Submit via XHR
387 event.element().request({
388 onSuccess: win,
389 onFailure: fail
390 });
391
392 if (load) {
393 load();
394 }
395 });
396 }
397 }
398
399
400 function cbi_t_add(section, tab) {
401 var t = document.getElementById('tab.' + section + '.' + tab);
402 var c = document.getElementById('container.' + section + '.' + tab);
403
404 if( t && c ) {
405 cbi_t[section] = (cbi_t[section] || [ ]);
406 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
407 }
408 }
409
410 function cbi_t_switch(section, tab) {
411 if( cbi_t[section] && cbi_t[section][tab] ) {
412 var o = cbi_t[section][tab];
413 var h = document.getElementById('tab.' + section);
414 for( var tid in cbi_t[section] ) {
415 var o2 = cbi_t[section][tid];
416 if( o.tab.id != o2.tab.id ) {
417 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
418 o2.container.style.display = 'none';
419 }
420 else {
421 if(h) h.value = tab;
422 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
423 o2.container.style.display = 'block';
424 }
425 }
426 }
427 return false
428 }
429
430 function cbi_t_update() {
431 var hl_tabs = [ ];
432
433 for( var sid in cbi_t )
434 for( var tid in cbi_t[sid] )
435 if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
436 cbi_t[sid][tid].tab.style.display = 'none';
437 }
438 else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
439 cbi_t[sid][tid].tab.style.display = '';
440
441 var t = cbi_t[sid][tid].tab;
442 t.className += ' cbi-tab-highlighted';
443 hl_tabs.push(t);
444 }
445
446 if( hl_tabs.length > 0 )
447 window.setTimeout(function() {
448 for( var i = 0; i < hl_tabs.length; i++ )
449 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
450 }, 750);
451 }
452
453
454 function cbi_validate_form(form, errmsg)
455 {
456 /* if triggered by a section removal or addition, don't validate */
457 if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
458 return true;
459
460 if( form.cbi_validators )
461 {
462 for( var i = 0; i < form.cbi_validators.length; i++ )
463 {
464 var validator = form.cbi_validators[i];
465 if( !validator() && errmsg )
466 {
467 alert(errmsg);
468 return false;
469 }
470 }
471 }
472
473 return true;
474 }
475
476 function cbi_validate_reset(form)
477 {
478 window.setTimeout(
479 function() { cbi_validate_form(form, null) }, 100
480 );
481
482 return true;
483 }
484
485 function cbi_validate_field(cbid, optional, type)
486 {
487 var field = document.getElementById(cbid);
488 var vldcb = cbi_validators[type];
489
490 if( field && vldcb )
491 {
492 var validator = function()
493 {
494 // is not detached
495 if( field.form )
496 {
497 field.className = field.className.replace(/ cbi-input-invalid/g, '');
498
499 // validate value
500 var value = (field.options) ? field.options[field.options.selectedIndex].value : field.value;
501 if( !(((value.length == 0) && optional) || vldcb(value)) )
502 {
503 // invalid
504 field.className += ' cbi-input-invalid';
505 return false;
506 }
507 }
508
509 return true;
510 };
511
512 if( ! field.form.cbi_validators )
513 field.form.cbi_validators = [ ];
514
515 field.form.cbi_validators.push(validator);
516 field.onblur = field.onkeyup = field.validate = validator;
517
518 validator();
519 }
520 }
521
522 if( ! String.serialize )
523 String.serialize = function(o)
524 {
525 switch(typeof(o))
526 {
527 case 'object':
528 // null
529 if( o == null )
530 {
531 return 'null';
532 }
533
534 // array
535 else if( o.length )
536 {
537 var i, s = '';
538
539 for( var i = 0; i < o.length; i++ )
540 s += (s ? ', ' : '') + String.serialize(o[i]);
541
542 return '[ ' + s + ' ]';
543 }
544
545 // object
546 else
547 {
548 var k, s = '';
549
550 for( k in o )
551 s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
552
553 return '{ ' + s + ' }';
554 }
555
556 break;
557
558 case 'string':
559 // complex string
560 if( o.match(/[^a-zA-Z0-9_,.: -]/) )
561 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
562
563 // simple string
564 else
565 return '"' + o + '"';
566
567 break;
568
569 default:
570 return o.toString();
571 }
572 }
573
574
575 if( ! String.format )
576 String.format = function()
577 {
578 if (!arguments || arguments.length < 1 || !RegExp)
579 return;
580
581 var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
582 var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
583
584 function esc(s, r) {
585 for( var i = 0; i < r.length; i += 2 )
586 s = s.replace(r[i], r[i+1]);
587 return s;
588 }
589
590 var str = arguments[0];
591 var out = '';
592 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j))/;
593 var a = b = [], numSubstitutions = 0, numMatches = 0;
594
595 while( a = re.exec(str) )
596 {
597 var m = a[1];
598 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
599 var pPrecision = a[6], pType = a[7];
600
601 numMatches++;
602
603 if (pType == '%')
604 {
605 subst = '%';
606 }
607 else
608 {
609 if (numSubstitutions++ < arguments.length)
610 {
611 var param = arguments[numSubstitutions];
612
613 var pad = '';
614 if (pPad && pPad.substr(0,1) == "'")
615 pad = leftpart.substr(1,1);
616 else if (pPad)
617 pad = pPad;
618
619 var justifyRight = true;
620 if (pJustify && pJustify === "-")
621 justifyRight = false;
622
623 var minLength = -1;
624 if (pMinLength)
625 minLength = parseInt(pMinLength);
626
627 var precision = -1;
628 if (pPrecision && pType == 'f')
629 precision = parseInt(pPrecision.substring(1));
630
631 var subst = param;
632
633 switch(pType)
634 {
635 case 'b':
636 subst = (parseInt(param) || 0).toString(2);
637 break;
638
639 case 'c':
640 subst = String.fromCharCode(parseInt(param) || 0);
641 break;
642
643 case 'd':
644 subst = (parseInt(param) || 0);
645 break;
646
647 case 'u':
648 subst = Math.abs(parseInt(param) || 0);
649 break;
650
651 case 'f':
652 subst = (precision > -1)
653 ? Math.round((parseFloat(param) || 0.0) * Math.pow(10, precision)) / Math.pow(10, precision)
654 : (parseFloat(param) || 0.0);
655 break;
656
657 case 'o':
658 subst = (parseInt(param) || 0).toString(8);
659 break;
660
661 case 's':
662 subst = param;
663 break;
664
665 case 'x':
666 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
667 break;
668
669 case 'X':
670 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
671 break;
672
673 case 'h':
674 subst = esc(param, html_esc);
675 break;
676
677 case 'q':
678 subst = esc(param, quot_esc);
679 break;
680
681 case 'j':
682 subst = String.serialize(param);
683 break;
684 }
685 }
686 }
687
688 out += leftpart + subst;
689 str = str.substr(m.length);
690 }
691
692 return out + str;
693 }