1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('./Validator');
|
7 |
|
8 | module.exports = class IpValidator extends Base {
|
9 |
|
10 | constructor (config) {
|
11 | super({
|
12 | ip4: true,
|
13 | ip6: true,
|
14 | ip4Pattern: '^(?:(?:2(?:[0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9])\.){3}(?:(?:2([0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9]))$',
|
15 | ip6Pattern: '^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$',
|
16 | ...config
|
17 | });
|
18 | }
|
19 |
|
20 | getMessage () {
|
21 | return this.createMessage(this.message, 'Invalid IP address');
|
22 | }
|
23 |
|
24 | getIp4NotAllowedMessage () {
|
25 | return this.createMessage(this.ip4NotAllowed, 'Value must not be an IPv4 address');
|
26 | }
|
27 |
|
28 | getIp6NotAllowedMessage () {
|
29 | return this.createMessage(this.ip6NotAllowed, 'Value must not be an IPv6 address');
|
30 | }
|
31 |
|
32 | async validateAttr (attr, model) {
|
33 | await super.validateAttr(...arguments);
|
34 | if (!model.hasError()) {
|
35 | model.set(attr, model.get(attr).toLowerCase());
|
36 | }
|
37 | }
|
38 |
|
39 | validateValue (value) {
|
40 | if (typeof value !== 'string' || value.length > 64) {
|
41 | return this.getMessage();
|
42 | }
|
43 | if ((new RegExp(this.ip4Pattern)).test(value)) {
|
44 | return this.ip4 ? null : this.getIp4NotAllowedMessage();
|
45 | }
|
46 | if ((new RegExp(this.ip6Pattern)).test(value)) {
|
47 | return this.ip6 ? null : this.getIp6NotAllowedMessage();
|
48 | }
|
49 | return this.getMessage();
|
50 | }
|
51 | }; |
\ | No newline at end of file |