validator/formFields.ts

46 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-10-11 15:13:40 +03:00
import { FieldCheck } from "./fieldChecks";
export class FieldsContainer {
fields = new Map<string, Field>();
/**
* Add field to container.
* @param {string} name - The field name.
* @param {string} value - The field value.
* @param {Array} checks - Array of necessary FieldCheck objects.
*/
addField(name: string, value: string, checks: FieldCheck[]) {
this.fields.set(name, new Field(value, checks));
}
}
export class Field {
value: string;
checks: FieldCheck[];
constructor(value: string, checks: FieldCheck[]) {
this.value = value;
this.checks = checks;
}
tryGetFirstError() {
let result = "";
this.checks.every((fieldCheck) => {
result = fieldCheck.check(this.value);
return result === ""; //break or continue every()
});
return result;
}
tryGetAllErrors() {
const result = this.checks.flatMap((fieldCheck) => {
const err = fieldCheck.check(this.value);
return err === "" ? [] : [err];
});
return result.join(", ");
}
}