4 var Validator
= baseclass
.extend({
5 __name__
: 'Validation',
7 __init__: function(field
, type
, optional
, vfunc
, validatorFactory
) {
9 this.optional
= optional
;
11 this.vstack
= validatorFactory
.compile(type
);
12 this.factory
= validatorFactory
;
15 assert: function(condition
, message
) {
17 this.field
.classList
.add('cbi-input-invalid');
22 this.field
.classList
.remove('cbi-input-invalid');
27 apply: function(name
, value
, args
) {
30 if (typeof(name
) === 'function')
32 else if (typeof(this.factory
.types
[name
]) === 'function')
33 func
= this.factory
.types
[name
];
40 return func
.apply(this, args
);
43 validate: function() {
44 /* element is detached */
45 if (!findParent(this.field
, 'body') && !findParent(this.field
, '[data-field]'))
48 this.field
.classList
.remove('cbi-input-invalid');
49 this.value
= (this.field
.value
!= null) ? this.field
.value
: '';
54 if (this.value
.length
=== 0)
55 valid
= this.assert(this.optional
, _('non-empty value'));
57 valid
= this.vstack
[0].apply(this, this.vstack
[1]);
60 this.field
.setAttribute('data-tooltip', _('Expecting: %s').format(this.error
));
61 this.field
.setAttribute('data-tooltip-style', 'error');
62 this.field
.dispatchEvent(new CustomEvent('validation-failure', { bubbles
: true }));
66 if (typeof(this.vfunc
) == 'function')
67 valid
= this.vfunc(this.value
);
70 this.assert(false, valid
);
71 this.field
.setAttribute('data-tooltip', valid
);
72 this.field
.setAttribute('data-tooltip-style', 'error');
73 this.field
.dispatchEvent(new CustomEvent('validation-failure', { bubbles
: true }));
77 this.field
.removeAttribute('data-tooltip');
78 this.field
.removeAttribute('data-tooltip-style');
79 this.field
.dispatchEvent(new CustomEvent('validation-success', { bubbles
: true }));
85 var ValidatorFactory
= baseclass
.extend({
86 __name__
: 'ValidatorFactory',
88 create: function(field
, type
, optional
, vfunc
) {
89 return new Validator(field
, type
, optional
, vfunc
, this);
92 compile: function(code
) {
100 for (var i
= 0; i
< code
.length
; i
++) {
106 switch (code
.charCodeAt(i
))
116 var label
= code
.substring(pos
, i
);
117 label
= label
.replace(/\\(.)/g, '$1');
118 label
= label
.replace(/^[ \t]+/g, '');
119 label
= label
.replace(/[ \t]+$/g, '');
121 if (label
&& !isNaN(label
)) {
122 stack
.push(parseFloat(label
));
124 else if (label
.match(/^(['"]).*\1$/)) {
125 stack
.push(label
.replace(/^(['"])(.*)\1$/, '$2'));
127 else if (typeof this.types
[label
] == 'function') {
128 stack
.push(this.types
[label
]);
132 L
.raise('SyntaxError', 'Unhandled token "%s"', label
);
139 depth
+= (code
.charCodeAt(i
) == 40);
144 if (typeof stack
[stack
.length
-2] != 'function')
145 L
.raise('SyntaxError', 'Argument list follows non-function');
147 stack
[stack
.length
-1] = this.compile(code
.substring(pos
, i
));
158 parseInteger: function(x
) {
159 return (/^-?\d+$/.test(x
) ? +x
: NaN
);
162 parseDecimal: function(x
) {
163 return (/^-?\d+(?:\.\d+)?$/.test(x
) ? +x
: NaN
);
166 parseIPv4: function(x
) {
167 if (!x
.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/))
170 if (RegExp
.$1 > 255 || RegExp
.$2 > 255 || RegExp
.$3 > 255 || RegExp
.$4 > 255)
173 return [ +RegExp
.$1, +RegExp
.$2, +RegExp
.$3, +RegExp
.$4 ];
176 parseIPv6: function(x
) {
177 if (x
.match(/^([a-fA-F0-9:]+):(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)) {
178 var v6
= RegExp
.$1, v4
= this.parseIPv4(RegExp
.$2);
183 x
= v6
+ ':' + (v4
[0] * 256 + v4
[1]).toString(16)
184 + ':' + (v4
[2] * 256 + v4
[3]).toString(16);
187 if (!x
.match(/^[a-fA-F0-9:]+$/))
190 var prefix_suffix
= x
.split(/::/);
192 if (prefix_suffix
.length
> 2)
195 var prefix
= (prefix_suffix
[0] || '0').split(/:/);
196 var suffix
= prefix_suffix
.length
> 1 ? (prefix_suffix
[1] || '0').split(/:/) : [];
198 if (suffix
.length
? (prefix
.length
+ suffix
.length
> 7)
199 : ((prefix_suffix
.length
< 2 && prefix
.length
< 8) || prefix
.length
> 8))
205 for (i
= 0, word
= parseInt(prefix
[0], 16); i
< prefix
.length
; word
= parseInt(prefix
[++i
], 16))
206 if (prefix
[i
].length
<= 4 && !isNaN(word
) && word
<= 0xFFFF)
211 for (i
= 0; i
< (8 - prefix
.length
- suffix
.length
); i
++)
214 for (i
= 0, word
= parseInt(suffix
[0], 16); i
< suffix
.length
; word
= parseInt(suffix
[++i
], 16))
215 if (suffix
[i
].length
<= 4 && !isNaN(word
) && word
<= 0xFFFF)
224 integer: function() {
225 return this.assert(!isNaN(this.factory
.parseInteger(this.value
)), _('valid integer value'));
228 uinteger: function() {
229 return this.assert(this.factory
.parseInteger(this.value
) >= 0, _('positive integer value'));
233 return this.assert(!isNaN(this.factory
.parseDecimal(this.value
)), _('valid decimal value'));
237 return this.assert(this.factory
.parseDecimal(this.value
) >= 0, _('positive decimal value'));
240 ipaddr: function(nomask
) {
241 return this.assert(this.apply('ip4addr', null, [nomask
]) || this.apply('ip6addr', null, [nomask
]),
242 nomask
? _('valid IP address') : _('valid IP address or prefix'));
245 ip4addr: function(nomask
) {
246 var re
= nomask
? /^(\d+\.\d+\.\d+\.\d+)$/ : /^(\d+\.\d+\.\d+\.\d+)(?:\/(\d+\.\d+\.\d+\.\d+)|\/(\d{1,2}))?$/,
247 m
= this.value
.match(re
);
249 return this.assert(m
&& this.factory
.parseIPv4(m
[1]) && (m
[2] ? this.factory
.parseIPv4(m
[2]) : (m
[3] ? this.apply('ip4prefix', m
[3]) : true)),
250 nomask
? _('valid IPv4 address') : _('valid IPv4 address or network'));
253 ip6addr: function(nomask
) {
254 var re
= nomask
? /^([0-9a-fA-F:.]+)$/ : /^([0-9a-fA-F:.]+)(?:\/(\d{1,3}))?$/,
255 m
= this.value
.match(re
);
257 return this.assert(m
&& this.factory
.parseIPv6(m
[1]) && (m
[2] ? this.apply('ip6prefix', m
[2]) : true),
258 nomask
? _('valid IPv6 address') : _('valid IPv6 address or prefix'));
261 ip4prefix: function() {
262 return this.assert(!isNaN(this.value
) && this.value
>= 0 && this.value
<= 32,
263 _('valid IPv4 prefix value (0-32)'));
266 ip6prefix: function() {
267 return this.assert(!isNaN(this.value
) && this.value
>= 0 && this.value
<= 128,
268 _('valid IPv6 prefix value (0-128)'));
272 return this.assert(this.apply('cidr4') || this.apply('cidr6'), _('valid IPv4 or IPv6 CIDR'));
276 var m
= this.value
.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,2})$/);
277 return this.assert(m
&& this.factory
.parseIPv4(m
[1]) && this.apply('ip4prefix', m
[2]), _('valid IPv4 CIDR'));
281 var m
= this.value
.match(/^([0-9a-fA-F:.]+)\/(\d{1,3})$/);
282 return this.assert(m
&& this.factory
.parseIPv6(m
[1]) && this.apply('ip6prefix', m
[2]), _('valid IPv6 CIDR'));
286 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})$/);
287 return this.assert(m
&& this.factory
.parseIPv4(m
[1]) && this.factory
.parseIPv4(m
[2]), _('IPv4 network in address/netmask notation'));
291 var m
= this.value
.match(/^([0-9a-fA-F:.]+)\/([0-9a-fA-F:.]+)$/);
292 return this.assert(m
&& this.factory
.parseIPv6(m
[1]) && this.factory
.parseIPv6(m
[2]), _('IPv6 network in address/netmask notation'));
295 ip6hostid: function() {
296 if (this.value
== "eui64" || this.value
== "random")
299 var v6
= this.factory
.parseIPv6(this.value
);
300 return this.assert(!(!v6
|| v6
[0] || v6
[1] || v6
[2] || v6
[3]), _('valid IPv6 host id'));
304 return this.assert(this.apply('ipmask4') || this.apply('ipmask6'),
305 _('valid network in address/netmask notation'));
308 ipmask4: function() {
309 return this.assert(this.apply('cidr4') || this.apply('ipnet4') || this.apply('ip4addr'),
310 _('valid IPv4 network'));
313 ipmask6: function() {
314 return this.assert(this.apply('cidr6') || this.apply('ipnet6') || this.apply('ip6addr'),
315 _('valid IPv6 network'));
319 var p
= this.factory
.parseInteger(this.value
);
320 return this.assert(p
>= 0 && p
<= 65535, _('valid port value'));
323 portrange: function() {
324 if (this.value
.match(/^(\d+)-(\d+)$/)) {
327 return this.assert(p1
<= p2
&& p2
<= 65535,
328 _('valid port or port range (port1-port2)'));
331 return this.assert(this.apply('port'), _('valid port or port range (port1-port2)'));
334 macaddr: function() {
335 return this.assert(this.value
.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null,
336 _('valid MAC address'));
339 host: function(ipv4only
) {
340 return this.assert(this.apply('hostname') || this.apply(ipv4only
== 1 ? 'ip4addr' : 'ipaddr', null, ['nomask']),
341 _('valid hostname or IP address'));
344 hostname: function(strict
) {
345 if (this.value
.length
<= 253)
347 (this.value
.match(/^[a-zA-Z0-9_]+$/) != null ||
348 (this.value
.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
349 this.value
.match(/[^0-9.]/))) &&
350 (!strict
|| !this.value
.match(/^_/)),
351 _('valid hostname'));
353 return this.assert(false, _('valid hostname'));
356 network: function() {
357 return this.assert(this.apply('uciname') || this.apply('host'),
358 _('valid UCI identifier, hostname or IP address'));
361 hostport: function(ipv4only
) {
362 var hp
= this.value
.split(/:/);
363 return this.assert(hp
.length
== 2 && this.apply('host', hp
[0], [ipv4only
]) && this.apply('port', hp
[1]),
364 _('valid host:port'));
367 ip4addrport: function() {
368 var hp
= this.value
.split(/:/);
369 return this.assert(hp
.length
== 2 && this.apply('ip4addr', hp
[0], [true]) && this.apply('port', hp
[1]),
370 _('valid IPv4 address:port'));
373 ipaddrport: function(bracket
) {
374 var m4
= this.value
.match(/^([^\[\]:]+):(\d+)$/),
375 m6
= this.value
.match((bracket
== 1) ? /^\[(.+)\]:(\d+)$/ : /^([^\[\]]+):(\d+)$/);
378 return this.assert(this.apply('ip4addr', m4
[1], [true]) && this.apply('port', m4
[2]),
379 _('valid address:port'));
381 return this.assert(m6
&& this.apply('ip6addr', m6
[1], [true]) && this.apply('port', m6
[2]),
382 _('valid address:port'));
389 return this.assert(v
.match(/^[a-fA-F0-9]{64}$/), _('valid hexadecimal WPA key'));
391 return this.assert((v
.length
>= 8) && (v
.length
<= 63), _('key between 8 and 63 characters'));
397 if (v
.substr(0, 2) === 's:')
400 if ((v
.length
== 10) || (v
.length
== 26))
401 return this.assert(v
.match(/^[a-fA-F0-9]{10,26}$/), _('valid hexadecimal WEP key'));
403 return this.assert((v
.length
=== 5) || (v
.length
=== 13), _('key with either 5 or 13 characters'));
406 uciname: function() {
407 return this.assert(this.value
.match(/^[a-zA-Z0-9_]+$/), _('valid UCI identifier'));
410 range: function(min
, max
) {
411 var val
= this.factory
.parseDecimal(this.value
);
412 return this.assert(val
>= +min
&& val
<= +max
, _('value between %f and %f').format(min
, max
));
416 return this.assert(this.factory
.parseDecimal(this.value
) >= +min
, _('value greater or equal to %f').format(min
));
420 return this.assert(this.factory
.parseDecimal(this.value
) <= +max
, _('value smaller or equal to %f').format(max
));
423 length: function(len
) {
424 var val
= '' + this.value
;
425 return this.assert(val
.length
== +len
,
426 _('value with %d characters').format(len
));
429 rangelength: function(min
, max
) {
430 var val
= '' + this.value
;
431 return this.assert((val
.length
>= +min
) && (val
.length
<= +max
),
432 _('value between %d and %d characters').format(min
, max
));
435 minlength: function(min
) {
436 return this.assert((''+this.value
).length
>= +min
,
437 _('value with at least %d characters').format(min
));
440 maxlength: function(max
) {
441 return this.assert((''+this.value
).length
<= +max
,
442 _('value with at most %d characters').format(max
));
448 for (var i
= 0; i
< arguments
.length
; i
+= 2) {
449 if (typeof arguments
[i
] != 'function') {
450 if (arguments
[i
] == this.value
)
451 return this.assert(true);
452 errors
.push('"%s"'.format(arguments
[i
]));
455 else if (arguments
[i
].apply(this, arguments
[i
+1])) {
456 return this.assert(true);
459 errors
.push(this.error
);
463 var t
= _('One of the following: %s');
465 return this.assert(false, t
.format('\n - ' + errors
.join('\n - ')));
469 for (var i
= 0; i
< arguments
.length
; i
+= 2) {
470 if (typeof arguments
[i
] != 'function') {
471 if (arguments
[i
] != this.value
)
472 return this.assert(false, '"%s"'.format(arguments
[i
]));
475 else if (!arguments
[i
].apply(this, arguments
[i
+1])) {
476 return this.assert(false, this.error
);
480 return this.assert(true);
484 this.value
= this.value
.replace(/^[ \t]*![ \t]*/, '');
486 if (arguments
[0].apply(this, arguments
[1]))
487 return this.assert(true);
489 return this.assert(false, _('Potential negation of: %s').format(this.error
));
492 list: function(subvalidator
, subargs
) {
493 this.field
.setAttribute('data-is-list', 'true');
495 var tokens
= this.value
.match(/[^ \t]+/g);
496 for (var i
= 0; i
< tokens
.length
; i
++)
497 if (!this.apply(subvalidator
, tokens
[i
], subargs
))
498 return this.assert(false, this.error
);
500 return this.assert(true);
503 phonedigit: function() {
504 return this.assert(this.value
.match(/^[0-9\*#!\.]+$/),
505 _('valid phone digit (0-9, "*", "#", "!" or ".")'));
508 timehhmmss: function() {
509 return this.assert(this.value
.match(/^[0-6][0-9]:[0-6][0-9]:[0-6][0-9]$/),
510 _('valid time (HH:MM:SS)'));
513 dateyyyymmdd: function() {
514 if (this.value
.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/)) {
515 var year
= +RegExp
.$1,
518 days_in_month
= [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
520 var is_leap_year = function(year
) {
521 return ((!(year
% 4) && (year
% 100)) || !(year
% 400));
524 var get_days_in_month = function(month
, year
) {
525 return (month
=== 2 && is_leap_year(year
)) ? 29 : days_in_month
[month
- 1];
528 /* Firewall rules in the past don't make sense */
529 return this.assert(year
>= 2015 && month
&& month
<= 12 && day
&& day
<= get_days_in_month(month
, year
),
530 _('valid date (YYYY-MM-DD)'));
534 return this.assert(false, _('valid date (YYYY-MM-DD)'));
537 unique: function(subvalidator
, subargs
) {
539 option
= findParent(ctx
.field
, '[data-widget][data-name]'),
540 section
= findParent(option
, '.cbi-section'),
541 query
= '[data-widget="%s"][data-name="%s"]'.format(option
.getAttribute('data-widget'), option
.getAttribute('data-name')),
544 section
.querySelectorAll(query
).forEach(function(sibling
) {
545 if (sibling
=== option
)
548 var input
= sibling
.querySelector('[data-type]'),
549 values
= input
? (input
.getAttribute('data-is-list') ? input
.value
.match(/[^ \t]+/g) : [ input
.value
]) : null;
551 if (values
!== null && values
.indexOf(ctx
.value
) !== -1)
556 return this.assert(false, _('unique value'));
558 if (typeof(subvalidator
) === 'function')
559 return this.apply(subvalidator
, null, subargs
);
561 return this.assert(true);
564 hexstring: function() {
565 return this.assert(this.value
.match(/^([a-f0-9][a-f0-9]|[A-F0-9][A-F0-9])+$/),
566 _('hexadecimal encoded value'));
575 return ValidatorFactory
;