aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/+admin/config/shared/batch-domains-validators.service.ts
blob: 154ef3a23ae3cd31170a5d9769cf3a79251a4b6a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { I18n } from '@ngx-translate/i18n-polyfill'
import { Validators, ValidatorFn } from '@angular/forms'
import { Injectable } from '@angular/core'
import { BuildFormValidator, validateHost } from '@app/shared'

@Injectable()
export class BatchDomainsValidatorsService {
  readonly DOMAINS: BuildFormValidator

  constructor (private i18n: I18n) {
    this.DOMAINS = {
      VALIDATORS: [ Validators.required, this.validDomains, this.isHostsUnique ],
      MESSAGES: {
        'required': this.i18n('Domain is required.'),
        'validDomains': this.i18n('Domains entered are invalid.'),
        'uniqueDomains': this.i18n('Domains entered contain duplicates.')
      }
    }
  }

  getNotEmptyHosts (hosts: string) {
    return hosts
      .split('\n')
      .filter((host: string) => host && host.length !== 0) // Eject empty hosts
  }

  private validDomains: ValidatorFn = (control) => {
    if (!control.value) return null

    const newHostsErrors = []
    const hosts = this.getNotEmptyHosts(control.value)

    for (const host of hosts) {
      if (validateHost(host) === false) {
        newHostsErrors.push(this.i18n('{{host}} is not valid', { host }))
      }
    }

    /* Is not valid. */
    if (newHostsErrors.length !== 0) {
      return {
        'validDomains': {
          reason: 'invalid',
          value: newHostsErrors.join('. ') + '.'
        }
      }
    }

    /* Is valid. */
    return null
  }

  private isHostsUnique: ValidatorFn = (control) => {
    if (!control.value) return null

    const hosts = this.getNotEmptyHosts(control.value)

    if (hosts.every((host: string) => hosts.indexOf(host) === hosts.lastIndexOf(host))) {
      return null
    } else {
      return {
        'uniqueDomains': {
          reason: 'invalid'
        }
      }
    }
  }
}