libs/core/src/lib/form-support/plugins-validation.ts
Properties |
validateAsync | |
Type |
function
|
import { AsyncValidatorFn, ValidatorFn } from '@angular/forms';
import { ValidationConfig, ValidationConfigItem, ValidationDefinitions } from './validation.model';
import { ValidationParam } from '../validation-config.model';
export type PluginValidatorType = `PLUGIN_${string}`;
interface BasePluginValidator {
type: PluginValidatorType;
defaultErrorMessage?: string;
}
export interface PluginValidator<VALIDATION_PARAM = ValidationParam> extends BasePluginValidator {
validate: (validationParam?: VALIDATION_PARAM) => ValidatorFn;
}
export interface AsyncPluginValidator<VALIDATION_PARAM = ValidationParam>
extends BasePluginValidator {
validateAsync: (validationParam?: VALIDATION_PARAM) => AsyncValidatorFn;
}
export type PluginValidatorUnion = PluginValidator | AsyncPluginValidator;
let __pluginValidators: PluginValidatorUnion[];
export function __setPluginValidators(pluginValidators: PluginValidatorUnion[]) {
if (__pluginValidators === undefined) {
__pluginValidators = pluginValidators;
}
}
function isAsyncValidator(validator: PluginValidatorUnion): validator is AsyncPluginValidator {
return (validator as AsyncPluginValidator).validateAsync !== undefined;
}
function extractPluginValidationFactory(pv: PluginValidatorUnion) {
return (item: ValidationConfigItem): ValidationConfig => ({
validator: isAsyncValidator(pv)
? pv.validateAsync(item.validationParam)
: pv.validate(item.validationParam),
validatorName: pv.type,
errorMessage: item.errorMessage || pv.defaultErrorMessage || '',
async: isAsyncValidator(pv),
validationParam: item.validationParam
});
}
export function getPluginValidations(): ValidationDefinitions {
return (__pluginValidators ?? []).reduce((acc, pv: PluginValidatorUnion) => {
const pluginValidatorValidation = {
// until TS supports regex in types, we cannot enforce that "type" field will be uppercase
[pv.type.toUpperCase()]: extractPluginValidationFactory(pv)
};
return { ...acc, ...pluginValidatorValidation };
}, {});
}