Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Validating Arguments in JavaScript Like a Boss

DZone 's Guide to

Validating Arguments in JavaScript Like a Boss

In this post, a senior dev shows how to use an open source library he created to simplify argument validation in JavaScript.

· Web Dev Zone ·
Free Resource

In software engineering, we try to discover and eliminate bugs as soon as possible. One of most important heuristics here is validation of input/output on functions and methods. If you are going with TypeScript or Flow, you are fine. But if not? Then we have to manually validate at least the input (arguments). But what would be the best way of doing this?

The first thing that comes to mind is the aproba library. It's "ridiculously" light-weight and equally popular:

import validate from "aproba";
function click( selector, x, y ) {
  validate( "SNN", arguments );
}

Simple, isn't it? For constraints we give a string where each character stands for a corresponding argument. So here we require the  selector to be a string ("S") and both coordinates to be numbers ("N").

But when it comes to optional arguments it gets quite obscure. For example, the Node.js function fs.createWriteStream(path[, options]) maintainers of aproba recommend describing this as SO|SS|OO|OS|S|O

First, it's not that easy to read and second we do not validate the structure of options, any object is considered valid.

Such limitations made me to come up with an alternative — byContract. It is based on a similar principle, but instead of single-character signature it expects JSDoc expressions.

So the function from above can validated like this:

import { validate, typedef } from "bycontract";

function createWriteStream( path, options ) {
  validate( arguments, ["string|Buffer", "string|WriteStreamOptions#" ]);
}

Meaning, we state that  path can be a string or an instance of Buffer and options can be a string or an object of the WriteStreamOptions type or missing (note the # at the end of the signature). Here WriteStreamOptions is a custom type representing write stream options. We can define it as follows:

typedef( "WriteStreamOptions", {
  flags: "string#",
  encoding: "string#",
  fd: "number#",
  mode: "number#",
  autoClose: "boolean#",
  start: "number#"
});

I find it quite neat already, but can we do better? As a diligent developer you probably provide your functions with JSDoc. Why not to simply reuse it? Examine how you can do it with byContract:

import { validateJsdoc, typedef } from "bycontract";

class Fs {
  @validateJsdoc(`
  /**
   * @param {string|Buffer} path
   * @param {string|WriteStreamOptions} options
   * @returns {<WriteStream>}
   */
  `)
  createWriteStream() {

  }
}

With validate in byContract you can validate either a list of arguments against a list of constraints or a single value against a single constraint. The function always returns the incoming value(s). That can be used, for example, for exit point validation:

function pdf() {
//...
return validate( returnValue, "Promise" );
}

What if a function accepts different combinations of argument types? Let's say we have a  compare function that takes either two strings or two arrays of strings. We just need to use validateCombo:

import { validateCombo } from "bycontract";
function compare( a, b ) {
  const CASE1 = [ "string", "string" ],
        CASE1 = [ "string[]", "string[]" ];
  validateCombo( arguments, [ CASE1, CASE2 ] );
}

But personally I like taking advantage of it when validting React.js action creators. Let's say we define constraints in a separate module:

/interface/index.js

export const GROUP_REF = { 
  id: "string" 
};
export const ENTITY = {
 editing: "boolean=", 
 disabled: "boolean="
};
export const GROUP = {
 title: "string=",
 tests: "*[]",
 ...GROUP_REF
};

Now we can reuse them in actions:

import { validate } from "bycontract";
import * as I from "interface";
 export const addGroup = ( data, ref = null ) => ({
  type: constants.ADD_GROUP,
  payload: {
    data: validate( data, { ...I.ENTITY, ...I.GROUP } ),
    ref: validate( ref, I.GROUP_REF )
  }
});

As you can see, I combined the abstract entity and group constraints { ...I.ENTITY, ...I.GROUP }. Thus, when I need to validate another entity subclass I can do this { ...I.ENTITY, ...I.TEST } or this { ...I.ENTITY, ...I.COMMAND }.

Recap

byContract covers literally all of my needs for argument validation. It's not that concise as aproba, but much more flexible and powerful.

One doesn't need to learn a new constraint syntax given you know already JSDoc. It's fast enough, but still can be turned off for production builds.

The library can be used as ES module, with Node.js, and as none-module in a browser.

Topics:
validation ,web dev ,javascript tutorial ,javascript arguments

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}