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

@cm-madlabs/ts-validator

v1.0.3

Published

true/false generic validator

Downloads

51

Readme

build npm version codecov publish to npm registry

TypeScript validator

Validate your value.

How to use

  • Basic usage: validate individual values using factory
  • Application: Create checkable interface, for example
  • Advanced: Create your own validator (and PR!)

install

yarn add @cm-madlabs/ts-validator

Validate individual values using factory

Factory is utility function-kit to validate your value.

import * as tv from '@cm-madlabs/ts-validator';

const age = '22a';
const result = tv.Factory.numberFormatValidator(
    'age',
    age,
    1,
    3,
).validate();

console.log(JSON.stringify(result));
// {"isValid":false,"report":{"rawValue":"22a","attribute":"age","expected":"pattern: /^[0-9]+$/","actual":"22a"}}


// We can applicate to throw error, for example.
if (!result.isValid) {
    throw new Error(JSON.stringify(result.report));
}
// Error: {"rawValue":"22a","attribute":"age","expected":"pattern: /^[0-9]+$/","actual":"22a"}
//       at Object.<anonymous>

In application usage

In your application, we recommend you to define a validatable domain object -- embedding this validators.

examples/user-domain.ts

import * as v from '@cm-madlabs/ts-validator';
import { Validator } from '@cm-madlabs/ts-validator';
import { ValidationResult } from '@cm-madlabs/ts-validator';

export abstract class Checkable {
    readonly validator: v.Validator;

    protected constructor(validator: Validator) {
        this.validator = validator;
    }

    check(): v.ValidationResult {
        return this.validator.validate();
    }
}

export class Name extends Checkable {
    static readonly key = 'name';

    constructor(readonly value: string) {
        super(v.Factory.lengthValidator(Name.key, value, 1, 100));
        this.value = value;
    }
}

export class LoginStatus extends Checkable {
    static readonly key = 'login_status';
    static readonly possibleValue = ['LoggedIn', 'Logout'];

    constructor(readonly value: string) {
        super(
            v.Factory.containsValidator(
                LoginStatus.key,
                value,
                LoginStatus.possibleValue,
            ),
        );
        this.value = value;
    }
}

export class UserDomainObject {
    name: Name;
    type: LoginStatus;

    static of({
        name,
        status,
    }: {
        name: string;
        status: string;
    }): UserDomainObject {
        const obj = new UserDomainObject();
        obj.name = new Name(name);
        obj.type = new LoginStatus(status);
        return obj;
    }

    validateAll(): ValidationResult[] {
        return Object.values(this).map((checkable: Checkable) =>
            checkable.check(),
        );
    }
}

const user = UserDomainObject.of({
    name: 'waddy',
    status: '',
});

const validateResult: ValidationResult[] = user.validateAll();
const invalids = validateResult.filter((r) => !r.isValid);
if (invalids.length) {
    const report = JSON.stringify(invalids.map((r) => r.report));
    console.error(report);
    throw new Error(JSON.stringify(report));
} else {
    // do your stuff
    console.log('do your stuff');
}

yarn ts-node examples/user-domain.ts will raise exception.

Advanced: Create your own validator

You can define your own validator and factory.

1. Define factory

If our repository validator make sense, your task is only to define composite factory. For example, length 5 or 7 postal code validator:

import {
    CompositeValidator,
    MaxLengthValidator,
    MinLengthValidator,
    OrCompositeValidator,
    Validator,
} from '@cm-madlabs/ts-validator';

export function postalCodeValidator(value: string): Validator {
    const key = 'postal_code';
    const minFive = new MinLengthValidator(key, value, 5);
    const maxFive = new MaxLengthValidator(key, value, 5);

    const minSeven = new MinLengthValidator(key, value, 7);
    const maxSeven = new MaxLengthValidator(key, value, 7);

    const five = new CompositeValidator(minFive, maxFive);
    const seven = new CompositeValidator(minSeven, maxSeven);

    return new OrCompositeValidator(five, seven);
}

2. Define validator

Otherwise, you can also define your own Validator:

export class SjisZenkakuValidator implements Validator {
    readonly name: string;
    readonly value: string;
    readonly patternSjis: RegExp = new RegExp('^[81-9f|e0-fc]+$');

    constructor(name: string, value: string) {
        this.name = name;
        this.value = value;
    }

    validate(): ValidationResult {
        const pattern = this.patternSjis;

        function check(v: string): boolean {
            
            const buffer = Buffer.from(v);
            const sjisBytes = encoding.convert(buffer, 'SJIS');

            // bytes
            const byteLength = sjisBytes.length;

            // get first
            const leftByte = (sjisBytes[0] & 0xff).toString(16);

            // mulibytes && character is valid
            return byteLength === 2 && pattern.test(leftByte);
        }

        const isValid = this.value
            .split('')
            .map(check)
            .reduce((pre, cur) => pre && cur, true);

        return {
            isValid,
            report: {
                attribute: this.name,
                rawValue: this.value,
                expected: `sjis pattern: ${this.patternSjis}`,
                actual: this.value,
            },
        };
    }
}