1 import { AbstractControl, ValidatorFn, Validators } from '@angular/forms'
2 import { BuildFormValidator } from './form-validator.model'
4 export function validateHost (value: string) {
5 // Thanks to http://stackoverflow.com/a/106223
6 const HOST_REGEXP = new RegExp(
7 '^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]).)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$'
10 return HOST_REGEXP.test(value)
13 export function validateHandle (value: string) {
14 if (!value) return false
16 return value.includes('@')
19 const validHosts: ValidatorFn = (control: AbstractControl) => {
20 if (!control.value) return null
23 const hosts = splitAndGetNotEmpty(control.value)
25 for (const host of hosts) {
26 if (validateHost(host) === false) {
27 errors.push($localize`${host} is not valid`)
32 if (errors.length === 0) return null
37 value: errors.join('. ') + '.'
42 const validHostsOrHandles: ValidatorFn = (control: AbstractControl) => {
43 if (!control.value) return null
46 const lines = splitAndGetNotEmpty(control.value)
48 for (const line of lines) {
49 if (validateHost(line) === false && validateHandle(line) === false) {
50 errors.push($localize`${line} is not valid`)
55 if (errors.length === 0) return null
58 validHostsOrHandles: {
60 value: errors.join('. ') + '.'
65 // ---------------------------------------------------------------------------
67 export function splitAndGetNotEmpty (value: string) {
70 .filter(line => line && line.length !== 0) // Eject empty hosts
73 export const unique: ValidatorFn = (control: AbstractControl) => {
74 if (!control.value) return null
76 const hosts = splitAndGetNotEmpty(control.value)
78 if (hosts.every((host: string) => hosts.indexOf(host) === hosts.lastIndexOf(host))) {
89 export const UNIQUE_HOSTS_VALIDATOR: BuildFormValidator = {
90 VALIDATORS: [ Validators.required, validHosts, unique ],
92 required: $localize`Domain is required.`,
93 validHosts: $localize`Hosts entered are invalid.`,
94 unique: $localize`Hosts entered contain duplicates.`
98 export const UNIQUE_HOSTS_OR_HANDLE_VALIDATOR: BuildFormValidator = {
99 VALIDATORS: [ Validators.required, validHostsOrHandles, unique ],
101 required: $localize`Domain is required.`,
102 validHostsOrHandles: $localize`Hosts or handles are invalid.`,
103 unique: $localize`Hosts or handles contain duplicates.`