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