1 import { I18n } from '@ngx-translate/i18n-polyfill'
2 import { Validators, ValidatorFn } from '@angular/forms'
3 import { Injectable } from '@angular/core'
4 import { BuildFormValidator, validateHost } from '@app/shared'
7 export class BatchDomainsValidatorsService {
8 readonly DOMAINS: BuildFormValidator
10 constructor (private i18n: I18n) {
12 VALIDATORS: [ Validators.required, this.validDomains, this.isHostsUnique ],
14 'required': this.i18n('Domain is required.'),
15 'validDomains': this.i18n('Domains entered are invalid.'),
16 'uniqueDomains': this.i18n('Domains entered contain duplicates.')
21 getNotEmptyHosts (hosts: string) {
24 .filter((host: string) => host && host.length !== 0) // Eject empty hosts
27 private validDomains: ValidatorFn = (control) => {
28 if (!control.value) return null
30 const newHostsErrors = []
31 const hosts = this.getNotEmptyHosts(control.value)
33 for (const host of hosts) {
34 if (validateHost(host) === false) {
35 newHostsErrors.push(this.i18n('{{host}} is not valid', { host }))
40 if (newHostsErrors.length !== 0) {
44 value: newHostsErrors.join('. ') + '.'
53 private isHostsUnique: ValidatorFn = (control) => {
54 if (!control.value) return null
56 const hosts = this.getNotEmptyHosts(control.value)
58 if (hosts.every((host: string) => hosts.indexOf(host) === hosts.lastIndexOf(host))) {