7 } from '@angular/forms';
9 import { I18n } from '@ngx-translate/i18n-polyfill';
10 import * as _ from 'lodash';
11 import { Observable, of as observableOf, timer as observableTimer } from 'rxjs';
12 import { map, switchMapTo, take } from 'rxjs/operators';
14 import { DimlessBinaryPipe } from '../pipes/dimless-binary.pipe';
15 import { FormatterService } from '../services/formatter.service';
17 export function isEmptyInputValue(value: any): boolean {
18 return value == null || value.length === 0;
21 export type existsServiceFn = (value: any) => Observable<boolean>;
23 export class CdValidators {
25 * Validator that performs email validation. In contrast to the Angular
26 * email validator an empty email will not be handled as invalid.
28 static email(control: AbstractControl): ValidationErrors | null {
29 // Exit immediately if value is empty.
30 if (isEmptyInputValue(control.value)) {
33 return Validators.email(control);
37 * Validator function in order to validate IP addresses.
38 * @param {number} version determines the protocol version. It needs to be set to 4 for IPv4 and
39 * to 6 for IPv6 validation. For any other number (it's also the default case) it will return a
40 * function to validate the input string against IPv4 OR IPv6.
41 * @returns {ValidatorFn} A validator function that returns an error map containing `pattern`
42 * if the validation check fails, otherwise `null`.
44 static ip(version: number = 0): ValidatorFn {
47 /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i;
48 const ipv6Rgx = /^(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}$/i;
51 return Validators.pattern(ipv4Rgx);
52 } else if (version === 6) {
53 return Validators.pattern(ipv6Rgx);
55 return Validators.pattern(new RegExp(ipv4Rgx.source + '|' + ipv6Rgx.source));
60 * Validator function in order to validate numbers.
61 * @returns {ValidatorFn} A validator function that returns an error map containing `pattern`
62 * if the validation check fails, otherwise `null`.
64 static number(allowsNegative: boolean = true): ValidatorFn {
66 return Validators.pattern(/^-?[0-9]+$/i);
68 return Validators.pattern(/^[0-9]+$/i);
73 * Validator function in order to validate decimal numbers.
74 * @returns {ValidatorFn} A validator function that returns an error map containing `pattern`
75 * if the validation check fails, otherwise `null`.
77 static decimalNumber(allowsNegative: boolean = true): ValidatorFn {
79 return Validators.pattern(/^-?[0-9]+(.[0-9]+)?$/i);
81 return Validators.pattern(/^[0-9]+(.[0-9]+)?$/i);
86 * Validator that performs SSL certificate validation.
87 * @returns {ValidatorFn} A validator function that returns an error map containing `pattern`
88 * if the validation check fails, otherwise `null`.
90 static sslCert(): ValidatorFn {
91 return Validators.pattern(
92 /^-----BEGIN CERTIFICATE-----(\n|\r|\f)((.+)?((\n|\r|\f).+)*)(\n|\r|\f)-----END CERTIFICATE-----[\n\r\f]*$/
97 * Validator that performs SSL private key validation.
98 * @returns {ValidatorFn} A validator function that returns an error map containing `pattern`
99 * if the validation check fails, otherwise `null`.
101 static sslPrivKey(): ValidatorFn {
102 return Validators.pattern(
103 /^-----BEGIN RSA PRIVATE KEY-----(\n|\r|\f)((.+)?((\n|\r|\f).+)*)(\n|\r|\f)-----END RSA PRIVATE KEY-----[\n\r\f]*$/
108 * Validator that requires controls to fulfill the specified condition if
109 * the specified prerequisites matches. If the prerequisites are fulfilled,
110 * then the given function is executed and if it succeeds, the 'required'
111 * validation error will be returned, otherwise null.
112 * @param {Object} prerequisites An object containing the prerequisites.
113 * To do additional checks rather than checking for equality you can
114 * use the extended prerequisite syntax:
115 * 'field_name': { 'op': '<OPERATOR>', arg1: '<OPERATOR_ARGUMENT>' }
116 * The following operators are supported:
125 * 'generate_key': true,
126 * 'username': 'Max Mustermann'
129 * ### Example - Extended prerequisites
132 * 'generate_key': { 'op': 'equal', 'arg1': true },
133 * 'username': { 'op': 'minLength', 'arg1': 5 }
136 * Only if all prerequisites are fulfilled, then the validation of the
137 * control will be triggered.
138 * @param {Function | undefined} condition The function to be executed when all
139 * prerequisites are fulfilled. If not set, then the {@link isEmptyInputValue}
140 * function will be used by default. The control's value is used as function
141 * argument. The function must return true to set the validation error.
142 * @return {ValidatorFn} Returns the validator function.
144 static requiredIf(prerequisites: object, condition?: Function | undefined): ValidatorFn {
145 let isWatched = false;
147 return (control: AbstractControl): ValidationErrors | null => {
148 if (!isWatched && control.parent) {
149 Object.keys(prerequisites).forEach((key) => {
150 control.parent.get(key).valueChanges.subscribe(() => {
151 control.updateValueAndValidity({ emitEvent: false });
158 // Check if all prerequisites met.
160 !Object.keys(prerequisites).every((key) => {
161 if (!control.parent) {
164 const value = control.parent.get(key).value;
165 const prerequisite = prerequisites[key];
166 if (_.isObjectLike(prerequisite)) {
168 switch (prerequisite['op']) {
170 result = _.isEmpty(value);
173 result = !_.isEmpty(value);
176 result = value === prerequisite['arg1'];
179 result = value !== prerequisite['arg1'];
182 if (_.isString(value)) {
183 result = value.length >= prerequisite['arg1'];
189 return value === prerequisite;
194 const success = _.isFunction(condition)
195 ? condition.call(condition, control.value)
196 : isEmptyInputValue(control.value);
197 return success ? { required: true } : null;
202 * Compose multiple validators into a single function that returns the union of
203 * the individual error maps for the provided control when the given prerequisites
206 * @param {Object} prerequisites An object containing the prerequisites as
211 * 'generate_key': true,
212 * 'username': 'Max Mustermann'
215 * @param {ValidatorFn[]} validators List of validators that should be taken
216 * into action when the prerequisites are met.
217 * @return {ValidatorFn} Returns the validator function.
219 static composeIf(prerequisites: object, validators: ValidatorFn[]): ValidatorFn {
220 let isWatched = false;
221 return (control: AbstractControl): ValidationErrors | null => {
222 if (!isWatched && control.parent) {
223 Object.keys(prerequisites).forEach((key) => {
224 control.parent.get(key).valueChanges.subscribe(() => {
225 control.updateValueAndValidity({ emitEvent: false });
230 // Check if all prerequisites are met.
232 !Object.keys(prerequisites).every((key) => {
233 return control.parent && control.parent.get(key).value === prerequisites[key];
238 return Validators.compose(validators)(control);
243 * Custom validation by passing a name for the error and a function as error condition.
245 * @param {string} error
246 * @param {Function} condition - a truthy return value will trigger the error
247 * @returns {ValidatorFn}
249 static custom(error: string, condition: Function): ValidatorFn {
250 return (control: AbstractControl): { [key: string]: any } => {
251 const value = condition.call(this, control.value);
253 return { [error]: value };
260 * Validate form control if condition is true with validators.
262 * @param {AbstractControl} formControl
263 * @param {Function} condition
264 * @param {ValidatorFn[]} conditionalValidators List of validators that should only be tested
265 * when the condition is met
266 * @param {ValidatorFn[]} permanentValidators List of validators that should always be tested
267 * @param {AbstractControl[]} watchControls List of controls that the condition depend on.
268 * Every time one of this controls value is updated, the validation will be triggered
271 formControl: AbstractControl,
273 conditionalValidators: ValidatorFn[],
274 permanentValidators: ValidatorFn[] = [],
275 watchControls: AbstractControl[] = []
277 conditionalValidators = conditionalValidators.concat(permanentValidators);
279 formControl.setValidators((control: AbstractControl): {
282 const value = condition.call(this);
284 return Validators.compose(conditionalValidators)(control);
286 if (permanentValidators.length > 0) {
287 return Validators.compose(permanentValidators)(control);
292 watchControls.forEach((control: AbstractControl) => {
293 control.valueChanges.subscribe(() => {
294 formControl.updateValueAndValidity({ emitEvent: false });
300 * Validator that requires that both specified controls have the same value.
301 * Error will be added to the `path2` control.
302 * @param {string} path1 A dot-delimited string that define the path to the control.
303 * @param {string} path2 A dot-delimited string that define the path to the control.
304 * @return {ValidatorFn} Returns a validator function that always returns `null`.
305 * If the validation fails an error map with the `match` property will be set
306 * on the `path2` control.
308 static match(path1: string, path2: string): ValidatorFn {
309 return (control: AbstractControl): { [key: string]: any } => {
310 const ctrl1 = control.get(path1);
311 const ctrl2 = control.get(path2);
312 if (!ctrl1 || !ctrl2) {
315 if (ctrl1.value !== ctrl2.value) {
316 ctrl2.setErrors({ match: true });
318 const hasError = ctrl2.hasError('match');
320 // Remove the 'match' error. If no more errors exists, then set
321 // the error value to 'null', otherwise the field is still marked
323 const errors = ctrl2.errors;
324 _.unset(errors, 'match');
325 ctrl2.setErrors(_.isEmpty(_.keys(errors)) ? null : errors);
333 * Asynchronous validator that requires the control's value to be unique.
334 * The validation is only executed after the specified delay. Every
335 * keystroke during this delay will restart the timer.
336 * @param serviceFn {existsServiceFn} The service function that is
337 * called to check whether the given value exists. It must return
338 * boolean 'true' if the given value exists, otherwise 'false'.
339 * @param serviceFnThis {any} The object to be used as the 'this' object
340 * when calling the serviceFn function. Defaults to null.
341 * @param {number|Date} dueTime The delay time to wait before the
342 * serviceFn call is executed. This is useful to prevent calls on
343 * every keystroke. Defaults to 500.
344 * @return {AsyncValidatorFn} Returns an asynchronous validator function
345 * that returns an error map with the `notUnique` property if the
346 * validation check succeeds, otherwise `null`.
349 serviceFn: existsServiceFn,
350 serviceFnThis: any = null,
352 ): AsyncValidatorFn {
353 return (control: AbstractControl): Observable<ValidationErrors | null> => {
354 // Exit immediately if user has not interacted with the control yet
355 // or the control value is empty.
356 if (control.pristine || isEmptyInputValue(control.value)) {
357 return observableOf(null);
359 // Forgot previous requests if a new one arrives within the specified
361 return observableTimer(dueTime).pipe(
362 switchMapTo(serviceFn.call(serviceFnThis, control.value)),
363 map((resp: boolean) => {
367 return { notUnique: true };
376 * Validator function for UUIDs.
377 * @param required - Defines if it is mandatory to fill in the UUID
378 * @return Validator function that returns an error object containing `invalidUuid` if the
379 * validation failed, `null` otherwise.
381 static uuid(required = false): ValidatorFn {
382 const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
383 return (control: AbstractControl): { [key: string]: any } | null => {
384 if (control.pristine && control.untouched) {
386 } else if (!required && !control.value) {
388 } else if (uuidRe.test(control.value)) {
391 return { invalidUuid: 'This is not a valid UUID' };
396 * A simple minimum validator vor cd-binary inputs.
398 * To use the validation message pass I18n into the function as it cannot
399 * be called in a static one.
401 static binaryMin(bytes: number): ValidatorFn {
402 return (control: AbstractControl): { [key: string]: (i18n: I18n) => string } | null => {
403 const formatterService = new FormatterService();
404 const currentBytes = new FormatterService().toBytes(control.value);
405 if (bytes <= currentBytes) {
408 const value = new DimlessBinaryPipe(formatterService).transform(bytes);
410 binaryMin: (i18n: I18n) => i18n(`Size has to be at least {{value}} or more`, { value })
416 * A simple maximum validator vor cd-binary inputs.
418 * To use the validation message pass I18n into the function as it cannot
419 * be called in a static one.
421 static binaryMax(bytes: number): ValidatorFn {
422 return (control: AbstractControl): { [key: string]: (i18n: I18n) => string } | null => {
423 const formatterService = new FormatterService();
424 const currentBytes = formatterService.toBytes(control.value);
425 if (bytes >= currentBytes) {
428 const value = new DimlessBinaryPipe(formatterService).transform(bytes);
430 binaryMax: (i18n: I18n) => i18n(`Size has to be at most {{value}} or less`, { value })
436 * Asynchronous validator that checks if the password meets the password
438 * @param userServiceThis The object to be used as the 'this' object
439 * when calling the 'validatePassword' method of the 'UserService'.
440 * @param usernameFn Function to get the username that should be
441 * taken into account.
442 * @param callback Callback function that is called after the validation
444 * @return {AsyncValidatorFn} Returns an asynchronous validator function
445 * that returns an error map with the `passwordPolicy` property if the
446 * validation check fails, otherwise `null`.
448 static passwordPolicy(
449 userServiceThis: any,
450 usernameFn?: Function,
451 callback?: (valid: boolean, credits?: number, valuation?: string) => void
452 ): AsyncValidatorFn {
453 return (control: AbstractControl): Observable<ValidationErrors | null> => {
454 if (control.pristine || control.value === '') {
455 if (_.isFunction(callback)) {
458 return observableOf(null);
461 if (_.isFunction(usernameFn)) {
462 username = usernameFn();
464 return observableTimer(500).pipe(
465 switchMapTo(_.invoke(userServiceThis, 'validatePassword', control.value, username)),
466 map((resp: { valid: boolean; credits: number; valuation: string }) => {
467 if (_.isFunction(callback)) {
468 callback(resp.valid, resp.credits, resp.valuation);
473 return { passwordPolicy: true };