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

ts-validity

v0.0.28

Published

Simple json validator by using user-defined validation rules

Downloads

215

Readme

ts-validity

Installation

npm install ts-validity       # npm
yarn add ts-validity          # yarn

Usage

Let's start with simple validation

Given interface

interface Account {
    name: string,
    age: number,
    email: string
}

Create the validation rule and validate the object

import { objectValidator, ValidationRule, minNumber, required, emailAddress } from "ts-validity";

const validationRule: ValidationRule<Account> = {
    name: [required("Account name is required.")],
    age: [required(), minNumber(17, "Should be at least 17 years old.")],
    email: [required(), emailAddress("Invalid email address")]
}

const account: Account = {
    name: "",
    age: 0,
    email: ""
}

const validationResult = objectValidator.validate(account, validationRule)

// The above validationResult value:
// {
//     message: "One or more validation errors occurred.",
//     isValid: false,
//     errors: {
//         name: ["Account name is required."],
//         age: ["This field is required.", "Should be at least 17 years old."],
//         email: ["This field is required.", "Invalid email address"],
//     }
// }

Notice that the validationResult.errors property, has the same property names as the account object, but its dataype is array of string. 

Nested object validation

import { objectValidator, ValidationRule, minNumber, required, emailAddress } from "ts-validity";

interface Person {
    name: string,
    age: number,
    child?: Person
    address?: {
        street: string,
        city: {
            name: string
            country: {
                name: string
                continent: {
                    name: string
                }
            }
        }
    }
}

const rule: ValidationRule<Person> = {
    name: [required()],
    age: [minNumber(20)],
    address: {
        street: [required()],
        city: {
            name: [required()],
            country: {
                name: [required()],
                continent: {
                    name: [required()],
                }
            }
        }
    },
    child: {
        name: [required()]
    }
}

const john: Person = {
    name: "",
    age: 0,
    address: {
        street: "",
        city: {
            name: "",
            country: {
                name: "",
                continent: {
                    name: ""
                }
            }
        }
    },
    child: {
        name: "",
        age: 0,
    }
}

const validationResult = objectValidator.validate(john, rule)

// validationResult = {
//     message: defaultMessage.errorMessage,
//     isValid: false,
//     errors: {
//         name: ["This field is required."],
//         age: ["The minimum value for this field is 20."],
//         address: {
//             street: ["This field is required."],
//             city: {
//                 name: ["This field is required."],
//                 country: {
//                     name: ["This field is required."],
//                     continent: {
//                         name: ["This field is required."],
//                     }
//                 }
//             }
//         },
//         child: {
//             name: ["This field is required."],
//         }
//     }
// }

Validate array property

import { objectValidator, ValidationRule, minNumber, required, emailAddress, arrayMinLen } from "ts-validity";

interface Product {
    name?: string
    units?: Unit[]
}

interface Unit {
    name: string,
    conversion: number,
}

const validationRule: ValidationRule<Product> = {
    name: [required()],
    units: {
        validators: [arrayMinLen(3, "Product uom has to be at least 3 units.")],
        validationRule: {
            name: [required()],
            conversion: [minNumber(1)]
        }
    }
}

const ironStick: Product = {
    name: "",
    units: [
        {
            name: "",
            conversion: 0
        },
        {
            name: "cm",
            conversion: 0
        }
    ]
}

const validationResult = objectValidator.validate(ironStick, validationRule)

// validationResult = {
//     message: defaultMessage.errorMessage,
//     isValid: false,
//     errors: {
//         name: ["This field is required."],
//         units: {
//             errors: ["Product uom has to be at least 3 units."],
//             errorsEach: [
//                 {
//                     index: 0,
//                     errors: {
//                         name: ["This field is required."],
//                         conversion: ["The minimum value for this field is 1."]
//                     },
//                     validatedObject: {
//                         name: "",
//                         conversion: 0
//                     }
//                 },
//                 {
//                     index: 1,
//                     errors: {
//                         conversion: ["The minimum value for this field is 1."]
//                     },
//                     validatedObject: {
//                         name: "cm",
//                         conversion: 0
//                     }
//                 }
//             ]
//         }
//     }
// }

Custom Property Validator

To use your own validator, you can use the propertyValidator function. The following is the signature of propertyValidator function:

export declare const propertyValidator: <TValue, TObject>(func: ValidateFunc<TValue, TObject>, errorMessage: string, validatorDescription?: string) => PropertyValidator<TValue, TObject>;

The existing built-in property validators, including the propertyValidator actually is a closure that returns a validate function, which is called by the objectValidator. The following is the signature of the ValidateFunc:

export type ValidateFunc<TValue, TObject> = (value: TValue, objRef?: TObject) => boolean

And this is the PropertyValidator type:

export type PropertyValidator<TValue, TObject> = {
    description: string;
    validate: ValidateFunc<TValue, TObject>;
    returningErrorMessage: string;
};

Usage

import { objectValidator, ValidationRule, propertyValidator } from "ts-validity";

interface Account {
    name: string,
}

const validationRule: ValidationRule<Account> = {
    name: [
        // Name length minimum is 5 char
        propertyValidator((value, object) => {
            return value.length >= 5
        }, "Name length minimum is 5 chars."),

        // Must contain A letter
        propertyValidator((value, object) => {
            return value.toLocaleLowerCase().includes("a")
        }, "Name must contain 'A' letter."),
    ],
}

const account: Account = {
    name: "John",
}

const validationResult = objectValidator.validate(account, validationRule)

// validationResult = {
//     message: "One or more validation errors occurred.",
//     isValid: false,
//     errors: {
//         name: ["Name length minimum is 5 chars.", "Name must contain 'A' letter."]
//     }
// }

Use existing npm validator package as custom validator

We can use and combine the existing popular validator from npm. In this example I use the validator package (https://www.npmjs.com/package/validator).

Installation

npm install validator
npm install -D @types/validator // if typescript

Usage

import { objectValidator, ValidationRule, propertyValidator } from "ts-validity";
import validator from 'validator';

interface Account {
    name: string,
    email: string,
    phone: string,
    password: string
}

const validationRule: ValidationRule<Account> = {
    name: [required()],
    // Combine the built-in validator and the 'validator' package
    email: [
        required(),
        propertyValidator((value, object) => {
            return validator.isEmail(value) // the 'validator' package
        }, "Not a valid email."),
    ],
    phone: [
        required(),
        propertyValidator((value, object) => {
            return validator.isMobilePhone(value, "en-AU") // the 'validator' package
        }, "Should be an AU mobile phone number format"),
    ],
    password: [
        required(),
        propertyValidator((value, object) => {
            // the 'validator' package
            return validator.isStrongPassword(value, {
                minLength: 8,
                minUppercase: 2
            })
        }, "Password should be 8 chars minimum, and has to contain at least 2 upper case."),
    ],
}

const account: Account = {
    name: "John",
    email: "valid@@email.com",
    phone: "123123123",
    password: "strongpassword"
}

const validationResult = objectValidator.validate(account, validationRule)

// validationResult = {
//     message: "One or more validation errors occurred.",
//     isValid: false,
//     errors: {
//         email: ["Not a valid email."],
//         phone: ["Should be an AU mobile phone number format"],
//         password: ["Password should be 8 chars minimum, and has to contain at least 2 upper case."]
//     }
// }

Available Built-in Property Validators

export {
    alphabetOnly,
    arrayMaxLen,
    arrayMinLen,
    elementOf,
    emailAddress,
    equalToPropertyValue,
    maxNumber,
    minNumber,
    maxSumOf,
    minSumOf,
    propertyValidator,
    regularExpression,
    required,
    stringMaxLen,
    stringMinLen,
}