69 lines
2.3 KiB
TypeScript
69 lines
2.3 KiB
TypeScript
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);
|
||
}
|