]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/shared-forms/form-validators/batch-domains-validators.service.ts
Migrate to $localize
[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 2import { ValidatorFn, Validators } from '@angular/forms'
67ed6552
C
3import { BuildFormValidator } from './form-validator.service'
4import { validateHost } from './host'
bb152476
RK
5
6@Injectable()
7export class BatchDomainsValidatorsService {
8 readonly DOMAINS: BuildFormValidator
9
66357162 10 constructor () {
bb152476
RK
11 this.DOMAINS = {
12 VALIDATORS: [ Validators.required, this.validDomains, this.isHostsUnique ],
13 MESSAGES: {
66357162
C
14 'required': $localize`Domain is required.`,
15 'validDomains': $localize`Domains entered are invalid.`,
16 'uniqueDomains': $localize`Domains entered contain duplicates.`
bb152476
RK
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) {
66357162 35 newHostsErrors.push($localize`${host} is not valid`)
bb152476
RK
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}