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'
8 export class BatchDomainsValidatorsService {
9 readonly DOMAINS: BuildFormValidator
11 constructor (private i18n: I18n) {
13 VALIDATORS: [ Validators.required, this.validDomains, this.isHostsUnique ],
15 'required': this.i18n('Domain is required.'),
16 'validDomains': this.i18n('Domains entered are invalid.'),
17 'uniqueDomains': this.i18n('Domains entered contain duplicates.')
22 getNotEmptyHosts (hosts: string) {
25 .filter((host: string) => host && host.length !== 0) // Eject empty hosts
28 private validDomains: ValidatorFn = (control) => {
29 if (!control.value) return null
31 const newHostsErrors = []
32 const hosts = this.getNotEmptyHosts(control.value)
34 for (const host of hosts) {
35 if (validateHost(host) === false) {
36 newHostsErrors.push(this.i18n('{{host}} is not valid', { host }))
41 if (newHostsErrors.length !== 0) {
45 value: newHostsErrors.join('. ') + '.'
54 private isHostsUnique: ValidatorFn = (control) => {
55 if (!control.value) return null
57 const hosts = this.getNotEmptyHosts(control.value)
59 if (hosts.every((host: string) => hosts.indexOf(host) === hosts.lastIndexOf(host))) {