@elmabs/elewise.elma365.ui.validation
v1.0.8
Published
Validation library for ELMA365
Maintainers
Readme
EleWise.ELMA365.UI.Validation
Содержание
Быстрый старт
import { ValidationManager, PropertyType } from '@elmabs/elewise.elma365.ui.validation';
// 1. Создаем менеджер валидации
const manager = new ValidationManager([
{
name: 'email',
display: 'Email',
type: PropertyType.String,
rules: {
required: true,
pattern: '^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$',
},
},
{
name: 'age',
display: 'Возраст',
type: PropertyType.Number,
rules: {
required: true,
min: 18,
max: 99,
},
},
]);
// 2. Выполняем валидацию
const result = manager.validate({
email: '[email protected]',
age: 25,
});
// 3. Обрабатываем результат
const valid = manager.validity(result);
if (valid) {
console.log('Данные валидны!');
} else {
console.error('Ошибки валидации:', result.errors);
}Основные типы
Тип свойства
class PropertyType {
static readonly Nullable: number = 0; // Тип принимающий null
static readonly String: number = 1; // Строка
static readonly Number: number = 2; // Число
static readonly Object: number = 3; // Объект
static readonly Boolean: number = 4; // Булевое
}Ошибка валидации свойства
type TPropertyValidationError = {
name: string; // Имя
display: string; // Отображаемое имя
message: string; // Сообщение
}Результат валидации
type TValidationResult = {
messages: string[]; // Сообщения
errors: TPropertyValidationError[]; // Ошибки
}Валидируемое свойство
type TValidationProperty = {
name: string; // Имя
display: string; // Отображаемое имя
type: number; // Тип свойства
rules: any; // Правила валидации
}Правила валидации
interface IValidationRules {
required: boolean; // Обязательное
}Правила валидации строки
interface IStringValidationRules extends IValidationRules {
pattern?: string; // Шаблон
minLenght?: number; // Минимальная длина
maxLenght?: number; // Максимальная длина
}Правила валидации числа
interface INumberValidationRules extends IValidationRules {
min?: number; // Минимальное значение
max?: number; // Максимальное значение
}Провайдер валидации
interface IValidationProvider {
readonly propertyType: number; // Тип свойства
validate(
property: TValidationProperty,
target: any): TPropertyValidationError | undefined; // Выполнить валидацию
}Менеджер валидации
class ValidationManager {
constructor(properties: TValidationProperty[]); // Конструктор
constructor(properties: TValidationProperty[], providers: IValidationProvider[]); // Конструктор
get providers(): ProviderCollection; // Провайдеры валидации
validate(target: any): TValidationResult; // Выполнить валидацию
validity(result: TValidationResult | undefined): boolean; // Проверить валидность
}
class ProviderCollection {
public entries(): IValidationProvider[]; // Получить провайдеры
public register(...providers: IValidationProvider[]); // Добавить провайдеры
}Свой провайдер валидации
// Расширенный список типов свойств
class PropertyTypeExt extends PropertyType {
static readonly ContactPhones: number = 100; // Телефоны представителя
}
type TContactPhones = [{ phone: { tel: string|undefined }}];
// Провайдер валидации телефонов представителя (Обязательность)
class RequiredContactPhonesValidator implements IValidationProvider {
readonly propertyType = PropertyTypeExt.ContactPhones;
public validate(property: TValidationProperty, target: any): TPropertyValidationError | undefined {
const rules: IValidationRules = property.rules;
if (rules.required) {
const phones: TContactPhones = target[property.name];
if (phones == undefined || phones.length == 0) {
return { name: property.name, display: property.display, message: 'Обязательное поле' };
}
const correctPhones = phones.filter(item => item.phone && item.phone.tel && item.phone.tel.length);
if (correctPhones.length == 0) {
return { name: property.name, display: property.display, message: 'Обязательное поле' };
}
}
return undefined;
}
}
const manager = new ValidationManager([{
name: 'phones', display: 'Телефон', type: PropertyTypeExt.ContactPhones, rules: { required: true }
}]);
manager.providers.register(new RequiredContactPhonesValidator());
const result = manager.validate({ phones: [{ phone:{ tel: undefined }}, { phone: { tel: '' }}]});
console.log(result.errors);
// Выведет:
// [
// { name: 'phones', display: 'Телефон', message: 'Обязательное поле' }
// ]