]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/shared-forms/form-validators/batch-domains-validators.service.ts
Update build steps for localization
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-forms / form-validators / batch-domains-validators.service.ts
CommitLineData
bb152476 1import { Injectable } from '@angular/core'
67ed6552
C
2import { ValidatorFn, Validators } from '@angular/forms'
3import { I18n } from '@ngx-translate/i18n-polyfill'
4import { BuildFormValidator } from './form-validator.service'
5import { validateHost } from './host'
bb152476
RK
6
7@Injectable()
8export 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}