diff options
Diffstat (limited to 'client/src/app/shared/shared-forms/form-validators/batch-domains-validators.service.ts')
-rw-r--r-- | client/src/app/shared/shared-forms/form-validators/batch-domains-validators.service.ts | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/client/src/app/shared/shared-forms/form-validators/batch-domains-validators.service.ts b/client/src/app/shared/shared-forms/form-validators/batch-domains-validators.service.ts new file mode 100644 index 000000000..f270b602b --- /dev/null +++ b/client/src/app/shared/shared-forms/form-validators/batch-domains-validators.service.ts | |||
@@ -0,0 +1,69 @@ | |||
1 | import { Injectable } from '@angular/core' | ||
2 | import { ValidatorFn, Validators } from '@angular/forms' | ||
3 | import { I18n } from '@ngx-translate/i18n-polyfill' | ||
4 | import { BuildFormValidator } from './form-validator.service' | ||
5 | import { validateHost } from './host' | ||
6 | |||
7 | @Injectable() | ||
8 | export class BatchDomainsValidatorsService { | ||
9 | readonly DOMAINS: BuildFormValidator | ||
10 | |||
11 | constructor (private i18n: I18n) { | ||
12 | this.DOMAINS = { | ||
13 | VALIDATORS: [ Validators.required, this.validDomains, this.isHostsUnique ], | ||
14 | MESSAGES: { | ||
15 | 'required': this.i18n('Domain is required.'), | ||
16 | 'validDomains': this.i18n('Domains entered are invalid.'), | ||
17 | 'uniqueDomains': this.i18n('Domains entered contain duplicates.') | ||
18 | } | ||
19 | } | ||
20 | } | ||
21 | |||
22 | getNotEmptyHosts (hosts: string) { | ||
23 | return hosts | ||
24 | .split('\n') | ||
25 | .filter((host: string) => host && host.length !== 0) // Eject empty hosts | ||
26 | } | ||
27 | |||
28 | private validDomains: ValidatorFn = (control) => { | ||
29 | if (!control.value) return null | ||
30 | |||
31 | const newHostsErrors = [] | ||
32 | const hosts = this.getNotEmptyHosts(control.value) | ||
33 | |||
34 | for (const host of hosts) { | ||
35 | if (validateHost(host) === false) { | ||
36 | newHostsErrors.push(this.i18n('{{host}} is not valid', { host })) | ||
37 | } | ||
38 | } | ||
39 | |||
40 | /* Is not valid. */ | ||
41 | if (newHostsErrors.length !== 0) { | ||
42 | return { | ||
43 | 'validDomains': { | ||
44 | reason: 'invalid', | ||
45 | value: newHostsErrors.join('. ') + '.' | ||
46 | } | ||
47 | } | ||
48 | } | ||
49 | |||
50 | /* Is valid. */ | ||
51 | return null | ||
52 | } | ||
53 | |||
54 | private isHostsUnique: ValidatorFn = (control) => { | ||
55 | if (!control.value) return null | ||
56 | |||
57 | const hosts = this.getNotEmptyHosts(control.value) | ||
58 | |||
59 | if (hosts.every((host: string) => hosts.indexOf(host) === hosts.lastIndexOf(host))) { | ||
60 | return null | ||
61 | } else { | ||
62 | return { | ||
63 | 'uniqueDomains': { | ||
64 | reason: 'invalid' | ||
65 | } | ||
66 | } | ||
67 | } | ||
68 | } | ||
69 | } | ||