46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
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(", ");
|
|
}
|
|
}
|