Skip to content

Instantly share code, notes, and snippets.

@mmitou
Created September 27, 2020 08:11
Show Gist options
  • Select an option

  • Save mmitou/cbf6ddbe06db06ec92a20b9bae476dd5 to your computer and use it in GitHub Desktop.

Select an option

Save mmitou/cbf6ddbe06db06ec92a20b9bae476dd5 to your computer and use it in GitHub Desktop.
type CheckValidFn = (v: any) => ValidationErrors | null;
const createValidatorFn = (...checkValids: CheckValidFn[]): ValidatorFn => {
const check = and(...checkValids);
const validator = (control: AbstractControl) => check(control.value);
return validator;
};
const and = (...checkValids: CheckValidFn[]): CheckValidFn => {
if (checkValids.length === 0) {
return (_: any) => null;
} else if (checkValids.length === 1) {
return checkValids[0];
}
return v => {
for (const check of checkValids) {
const verrs = check(v);
if (!!verrs) {
return verrs;
}
}
return null;
};
};
const or = (...checkValids: CheckValidFn[]): CheckValidFn => {
if (checkValids.length === 0) {
return (_: any) => ({ or: 'no validation' });
} else if (checkValids.length === 1) {
return checkValids[0];
}
return v => {
let errs: ValidationErrors[] = [];
for (const check of checkValids) {
const verr = check(v);
if (verr == null) {
return null;
} else {
errs.push(verr);
}
}
return { or: errs };
};
};
const createPredicate = (check: CheckValidFn): ((v: any) => boolean) => {
return v => !check(v);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment