npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@elmabs/elewise.elma365.ui.validation

v1.0.8

Published

Validation library for ELMA365

Readme

EleWise.ELMA365.UI.Validation

npm i @elmabs/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: 'Обязательное поле' }
// ]