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 🙏

© 2024 – Pkg Stats / Ryan Hefner

angular-typescript-validation

v2.0.0

Published

Stores all your client side and real time server validation logics in one place, plugin provides similar way of validation as aurelia does.

Downloads

61

Readme

angular-typescript-validation

Stores all your client side and real time server validation logics in one place, plugin provides similar way of validation as aurelia does.

Installation

npm install angular-typescript-validation --save or npm install https://github.com/VladislavSudakov/angular-typescript-validation.git --save

Configuration

Please take a look at src/config/ValidationConfig.ts for configurable options. If you wish to setup new options, you need to make a call to init provider with your configuration :

// import directives from library
import { ValidationConfig, InitValidationModuleProvider } from 'angular-typescript-validation';

let yourConfig = new ValidationConfig();
yourConfig.validationTimoutMs = 10;

InitValidationModuleProvider.init(yourConfig);

Basic Setup

Plugin contains three directives. ValidatableFieldDirective makes a watch on the model field, ValidationMessageDirective shows error messages related to some field and ValidationSummaryDirective shows the validation summary related to all form validation errors.

To make things work, you must register those directives first. This plugin does not provide any existing angular module for flexibility purposes.

// import directives from library
import { ValidatableFieldDirective, ValidationMessageDirective, ValidationSummaryDirective } from 'angular-typescript-validation';

// create your module first
let yourModule = angular.module('YourModuleName', []);

// setup directives, you can use different directive names if you wish to
yourModule.directive('validatableField',  ValidatableFieldDirective.factory);
yourModule.directive('validationMessage', ValidationMessageDirective.factory);
yourModule.directive('validationSummary', ValidationSummaryDirective.factory)

Usage

Simple validation example :

Create validatable model

// loginModel.ts

/**
 * login model.
 */
export class LoginModel {
    /**
     * username
     */
    public username: string;

    /**
     * password
     */
    public password: string;
}

Create validator for model

// loginValidator.ts

import {IValidator, IRulesCustomizer, RulesCustomizer } from 'angular-typescript-validation';

import {LoginModel} from 'models/login/loginModel';

/**
 * validator for login
 */
export class LoginValidator implements IValidator {
    /**
     * custom rules.
     */
    public get rulesCustomizer(): IRulesCustomizer {

        let customizer = new RulesCustomizer<LoginModel>();
        
        customizer.required(m => m.username, 'User name is required.');
        customizer.required(m => m.password, 'Password is required.');

        return customizer;
    }
}

Setup component ts

// loginComponent.ts

import 'angular';
import { IValidatableController, ValidationService, IValidationService, IRulesCustomizer, IValidator } from 'angular-typescript-validation';

import { LoginValidator } from 'validators/loginValidator';
import { LoginModel } from 'models/login/loginModel';

export class Login implements ng.IComponentOptions {
    public templateUrl: string;
    public controller: any;
    public controllerAs: string;
    public bindings: any;

    constructor() {        
        this.controller = LoginController;
        this.controllerAs = 'l';
        this.bindings = {
        };
    }
}

export class LoginController implements IValidatableController {
    
    /**
     * the validation service.
     */
    private validationService: IValidationService;

    /**
     * rulez of controller.
     */
    public rulesCustomizer: IRulesCustomizer;

    /**
     * The form element.
     */
    public form: any;

    /**
     * The one and only item
     * @binding
     */
    public item: LoginModel;

    static $inject = [
        '$scope'];

    /**
     * makes request to login.
     */
    public submit = () => {
        
        this.validationService.validate(this.item).then((result) => {
            if (result) {
                // validation is ok, we can make server request.  
            }
        });
    }

    /**
     * inits component.
     */
    constructor(
        private $scope: ng.IScope,
        validator = new LoginValidator()) {

        this.item = new LoginModel();    
        this.validationService = new ValidationService(this, $scope);
        this.rulesCustomizer = validator.rulesCustomizer;
    }
}

Setup component html

        <form name="l.form" class="ui large form">
            <div class="ui stacked segment">
                <div class="field">
                    <div class="ui left icon input">
                        <i class="user icon" />
                        <input type="text" name="username" ng-model="l.item.username" placeholder="Username" validatable-field="l" />
                    </div>
                </div>
                <div class="field">
                    <div class="ui left icon input">
                        <i class="lock icon" />
                        <input type="password" name="password" ng-model="l.item.password" placeholder="Password" validatable-field="l" />
                    </div>
                </div>
                <div class="ui fluid large blue submit button" ng-click="l.submit()">Login</div>
            </div>

            <validation-summary data-ctrl="l"></validation-summary>

        </form>

Notice the validatable-field directive is applied to inputs, the value of attribute is a controller passed inside. It ensures those inputs will be highlighted red on validation error. The name attribute is required on validatable inputs and should be the same as the name of the field inside model. This library uses semantic-ui, thus you may need to setup any css rules if you are using different components!!!. To make it work with other ui library or custom one, create a div with the field class, like in the example above, and it will be set to field error class if validation error occured. Then, just make your own css rules to style your inputs accordingly.

Another setup you will need to do is to set <form name="l.form", which assigns form variable to controller.

validation-summary directive displays error summary.

Group validation

There could be a case when you need to set one global validation per > 1 fields, so that error in one field will reflect errors on others, and success on one field would remove red highlight from other fields as well. This scenario could be achieved using the validatable-group attribute on your validatable inputs.

        <form name="l.form" class="ui large form">
            <div class="ui stacked segment">
                <div class="field">
                    <div class="ui left icon input">
                        <i class="user icon" />
                        <input type="text" name="username" ng-model="l.item.username" placeholder="Username" validatable-field="l" validatable-group="password" />
                    </div>
                </div>
                <div class="field">
                    <div class="ui left icon input">
                        <i class="lock icon" />
                        <input type="password" name="password" ng-model="l.item.password" placeholder="Password" validatable-field="l" validatable-group="username" />
                    </div>
                </div>
                <div class="ui fluid large blue submit button" ng-click="l.submit()">Login</div>
            </div>

            <validation-summary data-ctrl="l"></validation-summary>

        </form>
/**
 * validator for login
 */
export class LoginValidator implements IValidator {
    /**
     * custom rules.
     */
    public get rulesCustomizer(): IRulesCustomizer {

        let customizer = new RulesCustomizer<LoginModel>();
        
        let error: string = 'Some error';

        customizer.clientValidation(m => m.username, (entity: LoginModel, value: string) => {
           return this.validateGlobal(entity);
        }, error);

        customizer.clientValidation(m => m.password, (entity: LoginModel, value: string) => {
            return this.validateGlobal(entity);
         }, error);

        return customizer;
    }

    private validateGlobal(model: LoginModel): boolean {

        if (model.username !== '') {
            return false;
        }

        return model.password !== '';
    }
}

The example above will provide validation errors for both username and password only if username is not set.

Localized error messages

Library supports localization using the angular-translate library. You just need to setup this library and provide localized error message inside validator. There is already a translate filter set inside.

import {IValidator, IRulesCustomizer, RulesCustomizer } from 'angular-typescript-validation';
import {LoginModel} from 'models/login/loginModel';

/**
 * validator for login
 */
export class LoginValidator implements IValidator {
    /**
     * custom rules.
     */
    public get rulesCustomizer(): IRulesCustomizer {

        let customizer = new RulesCustomizer<LoginModel>();
        
        customizer.required(m => m.username, 'USER_NAME_REQURED');
        customizer.required(m => m.password, 'PASSWORD_REQURED');

        return customizer;
    }
}

Server side validation calls

The real time server validation calls are easy to implement using the same validator.

customizer.serverValidation(m => m.username, (entity: LoginModel, value: string) => {
            
            // here you will need to provide a Promise<bool> of your request to server
            // which checks for the username availability

            return this.service.isUserNameAvailable(value);

        }, 'User name must be unique.');