luci-base: form.js: handle SectionValue objects in GridSection modals
[project/luci.git] / modules / luci-base / htdocs / luci-static / resources / validation.js
1 'use strict';
2 'require baseclass';
3
4 function bytelen(x) {
5 return new Blob([x]).size;
6 }
7
8 var Validator = baseclass.extend({
9 __name__: 'Validation',
10
11 __init__: function(field, type, optional, vfunc, validatorFactory) {
12 this.field = field;
13 this.optional = optional;
14 this.vfunc = vfunc;
15 this.vstack = validatorFactory.compile(type);
16 this.factory = validatorFactory;
17 },
18
19 assert: function(condition, message) {
20 if (!condition) {
21 this.field.classList.add('cbi-input-invalid');
22 this.error = message;
23 return false;
24 }
25
26 this.field.classList.remove('cbi-input-invalid');
27 this.error = null;
28 return true;
29 },
30
31 apply: function(name, value, args) {
32 var func;
33
34 if (typeof(name) === 'function')
35 func = name;
36 else if (typeof(this.factory.types[name]) === 'function')
37 func = this.factory.types[name];
38 else
39 return false;
40
41 if (value != null)
42 this.value = value;
43
44 return func.apply(this, args);
45 },
46
47 validate: function() {
48 /* element is detached */
49 if (!findParent(this.field, 'body') && !findParent(this.field, '[data-field]'))
50 return true;
51
52 this.field.classList.remove('cbi-input-invalid');
53 this.value = (this.field.value != null) ? this.field.value : '';
54 this.error = null;
55
56 var valid;
57
58 if (this.value.length === 0)
59 valid = this.assert(this.optional, _('non-empty value'));
60 else
61 valid = this.vstack[0].apply(this, this.vstack[1]);
62
63 if (valid !== true) {
64 var message = _('Expecting: %s').format(this.error);
65 this.field.setAttribute('data-tooltip', message);
66 this.field.setAttribute('data-tooltip-style', 'error');
67 this.field.dispatchEvent(new CustomEvent('validation-failure', {
68 bubbles: true,
69 detail: {
70 message: message
71 }
72 }));
73 return false;
74 }
75
76 if (typeof(this.vfunc) == 'function')
77 valid = this.vfunc(this.value);
78
79 if (valid !== true) {
80 this.assert(false, valid);
81 this.field.setAttribute('data-tooltip', valid);
82 this.field.setAttribute('data-tooltip-style', 'error');
83 this.field.dispatchEvent(new CustomEvent('validation-failure', {
84 bubbles: true,
85 detail: {
86 message: valid
87 }
88 }));
89 return false;
90 }
91
92 this.field.removeAttribute('data-tooltip');
93 this.field.removeAttribute('data-tooltip-style');
94 this.field.dispatchEvent(new CustomEvent('validation-success', { bubbles: true }));
95 return true;
96 },
97
98 });
99
100 var ValidatorFactory = baseclass.extend({
101 __name__: 'ValidatorFactory',
102
103 create: function(field, type, optional, vfunc) {
104 return new Validator(field, type, optional, vfunc, this);
105 },
106
107 compile: function(code) {
108 var pos = 0;
109 var esc = false;
110 var depth = 0;
111 var stack = [ ];
112
113 code += ',';
114
115 for (var i = 0; i < code.length; i++) {
116 if (esc) {
117 esc = false;
118 continue;
119 }
120
121 switch (code.charCodeAt(i))
122 {
123 case 92:
124 esc = true;
125 break;
126
127 case 40:
128 case 44:
129 if (depth <= 0) {
130 if (pos < i) {
131 var label = code.substring(pos, i);
132 label = label.replace(/\\(.)/g, '$1');
133 label = label.replace(/^[ \t]+/g, '');
134 label = label.replace(/[ \t]+$/g, '');
135
136 if (label && !isNaN(label)) {
137 stack.push(parseFloat(label));
138 }
139 else if (label.match(/^(['"]).*\1$/)) {
140 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
141 }
142 else if (typeof this.types[label] == 'function') {
143 stack.push(this.types[label]);
144 stack.push(null);
145 }
146 else {
147 L.raise('SyntaxError', 'Unhandled token "%s"', label);
148 }
149 }
150
151 pos = i+1;
152 }
153
154 depth += (code.charCodeAt(i) == 40);
155 break;
156
157 case 41:
158 if (--depth <= 0) {
159 if (typeof stack[stack.length-2] != 'function')
160 L.raise('SyntaxError', 'Argument list follows non-function');
161
162 stack[stack.length-1] = this.compile(code.substring(pos, i));
163 pos = i+1;
164 }
165
166 break;
167 }
168 }
169
170 return stack;
171 },
172
173 parseInteger: function(x) {
174 return (/^-?\d+$/.test(x) ? +x : NaN);
175 },
176
177 parseDecimal: function(x) {
178 return (/^-?\d+(?:\.\d+)?$/.test(x) ? +x : NaN);
179 },
180
181 parseIPv4: function(x) {
182 if (!x.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/))
183 return null;
184
185 if (RegExp.$1 > 255 || RegExp.$2 > 255 || RegExp.$3 > 255 || RegExp.$4 > 255)
186 return null;
187
188 return [ +RegExp.$1, +RegExp.$2, +RegExp.$3, +RegExp.$4 ];
189 },
190
191 parseIPv6: function(x) {
192 if (x.match(/^([a-fA-F0-9:]+):(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)) {
193 var v6 = RegExp.$1, v4 = this.parseIPv4(RegExp.$2);
194
195 if (!v4)
196 return null;
197
198 x = v6 + ':' + (v4[0] * 256 + v4[1]).toString(16)
199 + ':' + (v4[2] * 256 + v4[3]).toString(16);
200 }
201
202 if (!x.match(/^[a-fA-F0-9:]+$/))
203 return null;
204
205 var prefix_suffix = x.split(/::/);
206
207 if (prefix_suffix.length > 2)
208 return null;
209
210 var prefix = (prefix_suffix[0] || '0').split(/:/);
211 var suffix = prefix_suffix.length > 1 ? (prefix_suffix[1] || '0').split(/:/) : [];
212
213 if (suffix.length ? (prefix.length + suffix.length > 7)
214 : ((prefix_suffix.length < 2 && prefix.length < 8) || prefix.length > 8))
215 return null;
216
217 var i, word;
218 var words = [];
219
220 for (i = 0, word = parseInt(prefix[0], 16); i < prefix.length; word = parseInt(prefix[++i], 16))
221 if (prefix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
222 words.push(word);
223 else
224 return null;
225
226 for (i = 0; i < (8 - prefix.length - suffix.length); i++)
227 words.push(0);
228
229 for (i = 0, word = parseInt(suffix[0], 16); i < suffix.length; word = parseInt(suffix[++i], 16))
230 if (suffix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
231 words.push(word);
232 else
233 return null;
234
235 return words;
236 },
237
238 types: {
239 integer: function() {
240 return this.assert(!isNaN(this.factory.parseInteger(this.value)), _('valid integer value'));
241 },
242
243 uinteger: function() {
244 return this.assert(this.factory.parseInteger(this.value) >= 0, _('positive integer value'));
245 },
246
247 float: function() {
248 return this.assert(!isNaN(this.factory.parseDecimal(this.value)), _('valid decimal value'));
249 },
250
251 ufloat: function() {
252 return this.assert(this.factory.parseDecimal(this.value) >= 0, _('positive decimal value'));
253 },
254
255 ipaddr: function(nomask) {
256 return this.assert(this.apply('ip4addr', null, [nomask]) || this.apply('ip6addr', null, [nomask]),
257 nomask ? _('valid IP address') : _('valid IP address or prefix'));
258 },
259
260 ip4addr: function(nomask) {
261 var re = nomask ? /^(\d+\.\d+\.\d+\.\d+)$/ : /^(\d+\.\d+\.\d+\.\d+)(?:\/(\d+\.\d+\.\d+\.\d+)|\/(\d{1,2}))?$/,
262 m = this.value.match(re);
263
264 return this.assert(m && this.factory.parseIPv4(m[1]) && (m[2] ? this.factory.parseIPv4(m[2]) : (m[3] ? this.apply('ip4prefix', m[3]) : true)),
265 nomask ? _('valid IPv4 address') : _('valid IPv4 address or network'));
266 },
267
268 ip6addr: function(nomask) {
269 var re = nomask ? /^([0-9a-fA-F:.]+)$/ : /^([0-9a-fA-F:.]+)(?:\/(\d{1,3}))?$/,
270 m = this.value.match(re);
271
272 return this.assert(m && this.factory.parseIPv6(m[1]) && (m[2] ? this.apply('ip6prefix', m[2]) : true),
273 nomask ? _('valid IPv6 address') : _('valid IPv6 address or prefix'));
274 },
275
276 ip4prefix: function() {
277 return this.assert(!isNaN(this.value) && this.value >= 0 && this.value <= 32,
278 _('valid IPv4 prefix value (0-32)'));
279 },
280
281 ip6prefix: function() {
282 return this.assert(!isNaN(this.value) && this.value >= 0 && this.value <= 128,
283 _('valid IPv6 prefix value (0-128)'));
284 },
285
286 cidr: function(negative) {
287 return this.assert(this.apply('cidr4', null, [negative]) || this.apply('cidr6', null, [negative]),
288 _('valid IPv4 or IPv6 CIDR'));
289 },
290
291 cidr4: function(negative) {
292 var m = this.value.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(-)?(\d{1,2})$/);
293 return this.assert(m && this.factory.parseIPv4(m[1]) && (negative || !m[2]) && this.apply('ip4prefix', m[3]),
294 _('valid IPv4 CIDR'));
295 },
296
297 cidr6: function(negative) {
298 var m = this.value.match(/^([0-9a-fA-F:.]+)\/(-)?(\d{1,3})$/);
299 return this.assert(m && this.factory.parseIPv6(m[1]) && (negative || !m[2]) && this.apply('ip6prefix', m[3]),
300 _('valid IPv6 CIDR'));
301 },
302
303 ipnet4: function() {
304 var m = this.value.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
305 return this.assert(m && this.factory.parseIPv4(m[1]) && this.factory.parseIPv4(m[2]), _('IPv4 network in address/netmask notation'));
306 },
307
308 ipnet6: function() {
309 var m = this.value.match(/^([0-9a-fA-F:.]+)\/([0-9a-fA-F:.]+)$/);
310 return this.assert(m && this.factory.parseIPv6(m[1]) && this.factory.parseIPv6(m[2]), _('IPv6 network in address/netmask notation'));
311 },
312
313 ip6hostid: function() {
314 if (this.value == "eui64" || this.value == "random")
315 return true;
316
317 var v6 = this.factory.parseIPv6(this.value);
318 return this.assert(!(!v6 || v6[0] || v6[1] || v6[2] || v6[3]), _('valid IPv6 host id'));
319 },
320
321 ipmask: function(negative) {
322 return this.assert(this.apply('ipmask4', null, [negative]) || this.apply('ipmask6', null, [negative]),
323 _('valid network in address/netmask notation'));
324 },
325
326 ipmask4: function(negative) {
327 return this.assert(this.apply('cidr4', null, [negative]) || this.apply('ipnet4') || this.apply('ip4addr'),
328 _('valid IPv4 network'));
329 },
330
331 ipmask6: function(negative) {
332 return this.assert(this.apply('cidr6', null, [negative]) || this.apply('ipnet6') || this.apply('ip6addr'),
333 _('valid IPv6 network'));
334 },
335
336 port: function() {
337 var p = this.factory.parseInteger(this.value);
338 return this.assert(p >= 0 && p <= 65535, _('valid port value'));
339 },
340
341 portrange: function() {
342 if (this.value.match(/^(\d+)-(\d+)$/)) {
343 var p1 = +RegExp.$1;
344 var p2 = +RegExp.$2;
345 return this.assert(p1 <= p2 && p2 <= 65535,
346 _('valid port or port range (port1-port2)'));
347 }
348
349 return this.assert(this.apply('port'), _('valid port or port range (port1-port2)'));
350 },
351
352 macaddr: function(multicast) {
353 var m = this.value.match(/^([a-fA-F0-9]{2}):([a-fA-F0-9]{2}:){4}[a-fA-F0-9]{2}$/);
354 return this.assert(m != null && !(+m[1] & 1) == !multicast,
355 multicast ? _('valid multicast MAC address') : _('valid MAC address'));
356 },
357
358 host: function(ipv4only) {
359 return this.assert(this.apply('hostname') || this.apply(ipv4only == 1 ? 'ip4addr' : 'ipaddr', null, ['nomask']),
360 _('valid hostname or IP address'));
361 },
362
363 hostname: function(strict) {
364 if (this.value.length <= 253)
365 return this.assert(
366 (this.value.match(/^[a-zA-Z0-9_]+$/) != null ||
367 (this.value.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
368 this.value.match(/[^0-9.]/))) &&
369 (!strict || !this.value.match(/^_/)),
370 _('valid hostname'));
371
372 return this.assert(false, _('valid hostname'));
373 },
374
375 network: function() {
376 return this.assert(this.apply('uciname') || this.apply('hostname') || this.apply('ip4addr') || this.apply('ip6addr'),
377 _('valid UCI identifier, hostname or IP address range'));
378 },
379
380 hostport: function(ipv4only) {
381 var hp = this.value.split(/:/);
382 return this.assert(hp.length == 2 && this.apply('host', hp[0], [ipv4only]) && this.apply('port', hp[1]),
383 _('valid host:port'));
384 },
385
386 ip4addrport: function() {
387 var hp = this.value.split(/:/);
388 return this.assert(hp.length == 2 && this.apply('ip4addr', hp[0], [true]) && this.apply('port', hp[1]),
389 _('valid IPv4 address:port'));
390 },
391
392 ipaddrport: function(bracket) {
393 var m4 = this.value.match(/^([^\[\]:]+):(\d+)$/),
394 m6 = this.value.match((bracket == 1) ? /^\[(.+)\]:(\d+)$/ : /^([^\[\]]+):(\d+)$/);
395
396 if (m4)
397 return this.assert(this.apply('ip4addr', m4[1], [true]) && this.apply('port', m4[2]),
398 _('valid address:port'));
399
400 return this.assert(m6 && this.apply('ip6addr', m6[1], [true]) && this.apply('port', m6[2]),
401 _('valid address:port'));
402 },
403
404 wpakey: function() {
405 var v = this.value;
406
407 if (v.length == 64)
408 return this.assert(v.match(/^[a-fA-F0-9]{64}$/), _('valid hexadecimal WPA key'));
409
410 return this.assert((v.length >= 8) && (v.length <= 63), _('key between 8 and 63 characters'));
411 },
412
413 wepkey: function() {
414 var v = this.value;
415
416 if (v.substr(0, 2) === 's:')
417 v = v.substr(2);
418
419 if ((v.length == 10) || (v.length == 26))
420 return this.assert(v.match(/^[a-fA-F0-9]{10,26}$/), _('valid hexadecimal WEP key'));
421
422 return this.assert((v.length === 5) || (v.length === 13), _('key with either 5 or 13 characters'));
423 },
424
425 uciname: function() {
426 return this.assert(this.value.match(/^[a-zA-Z0-9_]+$/), _('valid UCI identifier'));
427 },
428
429 range: function(min, max) {
430 var val = this.factory.parseDecimal(this.value);
431 return this.assert(val >= +min && val <= +max, _('value between %f and %f').format(min, max));
432 },
433
434 min: function(min) {
435 return this.assert(this.factory.parseDecimal(this.value) >= +min, _('value greater or equal to %f').format(min));
436 },
437
438 max: function(max) {
439 return this.assert(this.factory.parseDecimal(this.value) <= +max, _('value smaller or equal to %f').format(max));
440 },
441
442 length: function(len) {
443 return this.assert(bytelen(this.value) == +len,
444 _('value with %d characters').format(len));
445 },
446
447 rangelength: function(min, max) {
448 var len = bytelen(this.value);
449 return this.assert((len >= +min) && (len <= +max),
450 _('value between %d and %d characters').format(min, max));
451 },
452
453 minlength: function(min) {
454 return this.assert(bytelen(this.value) >= +min,
455 _('value with at least %d characters').format(min));
456 },
457
458 maxlength: function(max) {
459 return this.assert(bytelen(this.value) <= +max,
460 _('value with at most %d characters').format(max));
461 },
462
463 or: function() {
464 var errors = [];
465
466 for (var i = 0; i < arguments.length; i += 2) {
467 if (typeof arguments[i] != 'function') {
468 if (arguments[i] == this.value)
469 return this.assert(true);
470 errors.push('"%s"'.format(arguments[i]));
471 i--;
472 }
473 else if (arguments[i].apply(this, arguments[i+1])) {
474 return this.assert(true);
475 }
476 else {
477 errors.push(this.error);
478 }
479 }
480
481 var t = _('One of the following: %s');
482
483 return this.assert(false, t.format('\n - ' + errors.join('\n - ')));
484 },
485
486 and: function() {
487 for (var i = 0; i < arguments.length; i += 2) {
488 if (typeof arguments[i] != 'function') {
489 if (arguments[i] != this.value)
490 return this.assert(false, '"%s"'.format(arguments[i]));
491 i--;
492 }
493 else if (!arguments[i].apply(this, arguments[i+1])) {
494 return this.assert(false, this.error);
495 }
496 }
497
498 return this.assert(true);
499 },
500
501 neg: function() {
502 this.value = this.value.replace(/^[ \t]*![ \t]*/, '');
503
504 if (arguments[0].apply(this, arguments[1]))
505 return this.assert(true);
506
507 return this.assert(false, _('Potential negation of: %s').format(this.error));
508 },
509
510 list: function(subvalidator, subargs) {
511 this.field.setAttribute('data-is-list', 'true');
512
513 var tokens = this.value.match(/[^ \t]+/g);
514 for (var i = 0; i < tokens.length; i++)
515 if (!this.apply(subvalidator, tokens[i], subargs))
516 return this.assert(false, this.error);
517
518 return this.assert(true);
519 },
520
521 phonedigit: function() {
522 return this.assert(this.value.match(/^[0-9\*#!\.]+$/),
523 _('valid phone digit (0-9, "*", "#", "!" or ".")'));
524 },
525
526 timehhmmss: function() {
527 return this.assert(this.value.match(/^[0-6][0-9]:[0-6][0-9]:[0-6][0-9]$/),
528 _('valid time (HH:MM:SS)'));
529 },
530
531 dateyyyymmdd: function() {
532 if (this.value.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/)) {
533 var year = +RegExp.$1,
534 month = +RegExp.$2,
535 day = +RegExp.$3,
536 days_in_month = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
537
538 var is_leap_year = function(year) {
539 return ((!(year % 4) && (year % 100)) || !(year % 400));
540 }
541
542 var get_days_in_month = function(month, year) {
543 return (month === 2 && is_leap_year(year)) ? 29 : days_in_month[month - 1];
544 }
545
546 /* Firewall rules in the past don't make sense */
547 return this.assert(year >= 2015 && month && month <= 12 && day && day <= get_days_in_month(month, year),
548 _('valid date (YYYY-MM-DD)'));
549
550 }
551
552 return this.assert(false, _('valid date (YYYY-MM-DD)'));
553 },
554
555 unique: function(subvalidator, subargs) {
556 var ctx = this,
557 option = findParent(ctx.field, '[data-widget][data-name]'),
558 section = findParent(option, '.cbi-section'),
559 query = '[data-widget="%s"][data-name="%s"]'.format(option.getAttribute('data-widget'), option.getAttribute('data-name')),
560 unique = true;
561
562 section.querySelectorAll(query).forEach(function(sibling) {
563 if (sibling === option)
564 return;
565
566 var input = sibling.querySelector('[data-type]'),
567 values = input ? (input.getAttribute('data-is-list') ? input.value.match(/[^ \t]+/g) : [ input.value ]) : null;
568
569 if (values !== null && values.indexOf(ctx.value) !== -1)
570 unique = false;
571 });
572
573 if (!unique)
574 return this.assert(false, _('unique value'));
575
576 if (typeof(subvalidator) === 'function')
577 return this.apply(subvalidator, null, subargs);
578
579 return this.assert(true);
580 },
581
582 hexstring: function() {
583 return this.assert(this.value.match(/^([a-f0-9][a-f0-9]|[A-F0-9][A-F0-9])+$/),
584 _('hexadecimal encoded value'));
585 },
586
587 string: function() {
588 return true;
589 },
590
591 directory: function() {
592 return true;
593 },
594
595 file: function() {
596 return true;
597 },
598
599 device: function() {
600 return true;
601 }
602 }
603 });
604
605 return ValidatorFactory;