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