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

@thenja/verify

v1.1.0

Published

A simple way to verify parameters in typescript / javascript

Downloads

1

Readme

Test Coverage-shield-badge-1

Verifyjs

A simple way to verify parameters in typescript / javascript.

How to use

npm install @thenja/verify --save

import { verify } from '@thenja/verify';

let myAge = 33;
verify(myAge).number().min(18).max(99).isValid();

More examples:

verify({ a: 1 }).equals({ a: 1 }).isValid();

let myAge = 17;
verify(myAge).min(18).isValidOrThrowError('You need to be at least 18 to drink beer');

// throw a custom error
verify(myEmail).email().isValidOrThrowError(new Error('Invalid email'));

verify(myPassword).string().min(8).notEquals('password').isValidOrThrowError();

let name = null;
name = verify(name).isSetOrUseDefault('Unknown');

// specify a parameter name so the error message thrown is useful
let myAge = '33';
verify(myAge, 'age').number().isValidOrThrowError();
// The error that will get thrown will read:
//   Parameter (age) is not a number
// Where as, if you did not pass a parameter name, the error message would read:
//   Parameter is not a number

verify('23').number().isValid(); // will return false
verify('23').number(true).isValid(); // will return true

Using the distribution file (dist/verify.min.js)

<script src="../dist/verify.min.js" type="text/javascript"></script>

Thenja.verify(10).equals(12).isValid()

verify(parameter: any, parameterName?: string)

Everything starts with the verify function. This method accepts two arguments, the first being the parameter you want to verify and the second argument is the name of the parameter, this is optional. This helps with returning useful error messages (check the examples below).

Chainable validation methods

The chainable validation methods have to be used with isValid(), isNotValid() or isValidOrThrowError()

|Method | Description |-------|-------------| |type(type: string) | verify the parameter is of a certain type. Available types: string, number, int, array, boolean, json, email | |string() | verify the parameter is a string. Alias for .type('string') | |number(allowNumberAsString: boolean = false) | verify the parameter is a number. Alias for .type('number') | |int(allowIntAsString: boolean = false) | verify the parameter is an integer. Alias for .type('int') | |array() | verify the parameter is an array. Alias for .type('array') | |boolean() | verify the parameter is a boolean. Alias for .type('boolean') | |json() | verify the parameter is a json object. Alias for .type('json') | |email() | verify the parameter is a valid email address. Alias for .type('email') | |min(value: number) | verify the parameter meets the minimum value required, can only be used with data types: string, number and array | |max(value: number) | verify the parameter does not exceed the maximum allowed value, can only be used with data types: string, number and array | |equals(value: any) | verify the parameter eqauls the value | |notEquals(value: any) | verify the parameter does not equal the value | |lengthEquals(value: number) | verify the parameter length equals the value, can only be used with data types: string and array | |empty() | verify the parameter is empty, can only be used with data types: string, array and json | |notEmpty() | verify the parameter is not empty, can only be used with data types: string, array and json |

Methods

|Method | Description | |-------|-------------| |isValid() | determine if the chainable validation methods evaluate to true | |isNotValid() | determine if any of the chainable validation methods evaluate to false | |isNotValidOrThrowError(err?: any) | determine if the chainable validation methods evaluate to true, if not, an error is thrown. |

The below methods can not be used with the chainable validation methods.

|Method | Description | |-------|-------------| |isDefined() | determine if the parameter is defined (not equal to undefined) | |isDefinedOrThrowError(err?: any) | determine if the parameter is defined (not equal to undefined), otherwise throw an error | |isNotDefined() | determine if the parameter equals undefined | |isSet() | determine if the parameter is set (not equal to undefined or null) | |isSetOrThrowError(err?: any) | determine if the parameter is set (not equal to undefined or null), otherwise throw an error | |isNotSet() | determine if the parameter is equal to undefined or null | |isSetOrUseDefault(defaultValue: any) | determine if the parameter is set, if not, set it to the default value | |isTruthy() | determine if the parameter equals either: "1", >= 1, true, "true" or "yes" | |isFalsey() | determine if the parameter equals either: "0", "false", "no", false, < 1, "nil" |

Use cases:

Most of the time you should be validating your parameters in a function or parameters passed to an API, verifyjs allows you to do this in a clean and simple manner.

Validating a methods parameters:

class Person {
  constructor(private name: string, private age: number) {}

  setDetails(name: string, age: number) {
    verify(name, 'name').isSetOrThrowError();
    verify(age, 'age').min(0).max(99).isValidOrThrowError();
    
    this.name = name;
    this.age = age;
  }
}

// somewhere else in your code
try {
  let person = new Person();
  person.setDetails('Nathan', 190);
} catch(err) {
  // handle error
}

Using with a Promise:

You can easily use verifyjs inside a promise, any errors thrown inside the Promise will call the catch() method. However, there are a few use cases where it wont work, they are listed below in the typescript code.

let myFunc = () => {
  return new Promise((resolve, reject) => {
    verify(null, 'age').isSetOrThrowError();
    resolve(true);
  });
};

myFunc().then(() => {}).catch((err) => {
  // catch will be called with the thrown error: Parameter (age) is not set.
});

////////////////////////////

// Errors thrown inside asynchronous functions will act like uncaught errors
let myFunc = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // this error will not call the catch() method of the promise
      verify(null, 'age').isSetOrThrowError();
      resolve();
    }, 1000);
  });
};

Development

npm run init - Setup the module for development (run once after cloning)

npm run dev - Run this command when you want to work on this module. It will compile typescript, run tests and watch for file changes.

Distribution

npm run build -- -v <version> - Create a distribution build of the module.

-v (version) - [Optional] Either "patch", "minor" or "major". Increase the version number in the package.json file.

The build command creates a /compiled directory which has all the javascript compiled code and typescript definitions. As well, a /dist directory is created that contains a minified javascript file.

Testing

Tests are automatically ran when you do a build.

npm run test - Run the tests. The tests will be ran in a nodejs environment. You can run the tests in a browser environment by opening the file /spec/in-browser/SpecRunner.html.

License

MIT © Nathan Anderson