validator/fieldChecks.ts
2023-10-11 15:13:40 +03:00

69 lines
2.3 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

export class FieldCheck {
error = "";
constructor(error: string) {
this.error = error;
}
check(val: string) {
throw new Error("check() not implemented");
return "";
}
}
class FieldCheckRegex extends FieldCheck {
regex = /none/;
constructor(regex: RegExp, error: string) {
super(error);
this.regex = regex;
}
check(val: string) {
if (!this.regex.test(val)) return this.error;
return "";
}
}
class FieldCheckMaxLength extends FieldCheck {
maxLength = 0;
constructor(maxLength: number) {
super(`Максимальная длина равна ${maxLength}.`);
this.maxLength = maxLength;
}
check(val: string) {
if (val.length > this.maxLength) return this.error;
return "";
}
}
class FieldCheckMinLength extends FieldCheck {
minLength = 0;
constructor(minLength: number) {
super(`Минимальная длина равна ${minLength}.`);
this.minLength = minLength;
}
check(val: string) {
if (val.length < this.minLength) return this.error;
return "";
}
}
export class FieldChecks {
static nonEmpty = new FieldCheckRegex(/\S+/, "Поле не может быть пустым.");
static onlyLatinLettersWhitespaces = new FieldCheckRegex(/^[A-Za-z\s]+$/, "Разрешены только Латинские буквы и пробелы.");
static onlyLettersWhitespaces = new FieldCheckRegex(/^[A-Za-zА-Яа-я\s]+$/, "Разрешены только буквы и пробелы.");
static onlyLatinLettersNumbersUnderscores = new FieldCheckRegex(
/^[A-Za-z0-9_\s]+$/,
"Разрешены только Латинские буквы, цифры и нижнее подчёркивание."
);
static email = new FieldCheckRegex(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, "Проверьте почтовый адрес.");
static noSpecialChars = new FieldCheckRegex(/^[A-Za-z0-9\s.,()!%]+$/, "Специальные символы не разрешены.");
static maxLength = (maxLength: number) => new FieldCheckMaxLength(maxLength);
static minLength = (minLength: number) => new FieldCheckMinLength(minLength);
}