lewisgcm / typescript-validate

Typescript annotations for validation and sanitization

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

TypeScript Validation and Sanitization Decorators

Build Status npm version npm Coverage Status License Type

Getting Started

Using this package is simple and can be achevied with the following:

npm install typescript-validate

Contributing

Please contribute if you have any additions.

Quick Start

import { Sanitize, Validate, Sanitizor, Validator, SanitizationType } from "typescript-validate";

class User {

    @Sanitize([
        SanitizationType.AlphaNumeric
    ])
    @Validate({
        String: {
            MinLength: 1,
            MaxLength: 5
        }
    })
    public Username: string;

    @Validate({
        Number: {
            Min: 5,
            Max: 10
        }
    })
    public age: number;

    @Validate({
        URL: true,
        Pattern: /^.*google.com/
    })
    private website: string;

    @Validate({
        Time: {
            Format: "dd/mm/YY"
        }
    })
    private dob: string;

    @Validate({
        Time: {
            Fromat: "HH:MM:SS",
            Locale: "en" //If textual dates are supplied only english are valid
        }
    })
    private sentAt: string;

    @Validate({
        CreditCard: [ CreditCardType.Mastercard, CreditCardType.Visa ]
    })
    private _creditCard: string;
}

var user = new User();
t.Username = "Hello World"; //invalid
Sanitizor.Sanitize( user );
Validator.Valid( user ); //returns false

##Validators Validators can be used on classes by adding the @Validate decorator to class properties. The class can the be validated using the Validator.Valid function on the instantiated object of that class. The following validators are supported:

  • Email
  • CreditCard
  • Time
  • Number
  • String
  • PostCode
  • Pattern
  • URL

##Sanitizors Sanitizors are used for sanitizing class properties before operating on them. Add sanitizors using the @Sanitize decorator to class properties and then call the Saniztor.Santize method on an instantiated object of that class. The santizor will then update each of the decorator properties based on the santizor used.

  • Trim - Trim trailing and leading spaces, tabs and newlines
  • UpperCase - Transform the text to uppercase
  • LowerCase - Transform the text to lowercase
  • Numeric - Strip all non numeric
  • Alpha - Strip all non alpha
  • AlphaNumeric - Strip all non alpha and numeric
  • NoSpaces - Strip all spaces

About

Typescript annotations for validation and sanitization

License:GNU Lesser General Public License v3.0


Languages

Language:TypeScript 100.0%