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

jason-validator

v0.1.0

Published

A composable validation library for TypeScript and JavaScript with amazing type support.

Downloads

45

Readme

jason

A Deno module for building composable validators for your JavaScript data with fluid TypeScript support.

Usage

To use jason, simply import it from deno.land. We strongly advise to import the module under the namespace of jason to avoid conflicts with some TypeScript types and our methods.

import * as jason from "https://deno.land/x/jason/mod.ts";

Examples

Find all examples in the examples directory.

Guides

User Object

First, let's look at the format of the data we are going to be parsing:

{
  "id": "user-0128432", // must begin with 'user-'
  "username": "theskyisblue", // 4 - 16 characters
  "age": 23 // must be at least '0'
}

Now, let's build out a validator:

const userSchema = jason.object({
  id: jason.string({ startsWith: "user-" }),
  username: jason.string({ length: { min: 4, max: 16 } }), // these are inclusive
  age: jason.number({ min: 0 }),
});

After that, you might want to be able to create a TypeScript interface/type that describes the shape of the User object. With jason, it's extremely simple to do by just importing our utility GetJasonType type:

import type { GetJasonType } from "https://deno.land/x/jason/mod.ts";

// ~~~ user schema definition ~~~

type User = GetJasonType<typeof userSchema>;

Now, we you get the type information for User, it should look like this:

type User = {
  id: string;
  username: string;
  age: number;
} & {}; // the `& {}` is from a TypeScript trick used to create optional properties

And now, let's finally validate our original data with our schema definition:

userSchema
  .validate({
    id: "user-0128432",
    username: "4to16characters",
    age: 23,
  })
  .tryThrowErrors();

After you run that, you will see that we get no errors! However, now let's test with some incorrect data:

userSchema
  .validate({
    id: "2353",
    username: "asd",
    age: -3,
  })
  .tryThrowErrors();

After that, you'll see the following messages:

'id': '2353' did not start with 'user-'

'username': 'asd' had a length less than the minimum length of '4'

'age': '-3' is not greater than or equal to '0'

error: Uncaught TypeError: Failed to validate data. There is most likely more information above.

FAQ

How do I have optional properties?

All you need to do is wrap the given property with the jason.optional composable:

const schema = jason.object({
  name: jason.string(),
  friends: jason.optional(jason.array(jason.string())),
});

schema
  .validate({
    name: "Jon Doe",
    friends: ["Jane Doe", "Billy Bob"],
  })
  .tryThrowErrors();

schema
  .validate({
    name: "Jon Doe",
  })
  .tryThrowErrors();

I am getting type errors when passing in parameters into Validator.validate. What am I doing wrong?

The Validator.validate method is actually type-checked to only take in values that match the TypeScript version of your schema. This is to help by giving editor hints on properties and also help you find errors when you are validating data that would never pass validation. However, you can always just cast your value to any if you want to forgo type-checking.

How do I use it with JSON?

All you need to do is first parse the JSON with JSON.parse() (or just pass in Response#json if you're using the Fetch API) into the validate method of your schema:

const schema = jason.labelled(
  "User",
  jason.object({
    name: jason.string(),
    age: jason.number({ min: 0 }),
  }),
);

const body = '{ "name": "awesomeguy23", "age": 23 }';
const data = JSON.parse(body);

schema.validate(data).tryThrowErrors();

Contributing

Please format your code using deno fmt and make sure you run deno test before sending a pull request.

License

MIT