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