LGTM: A Validation Library for JavaScript

Simple asynchronous object validation for node.js and the browser.

Written by Brian Donovan.

Validating user input and displaying error messages is a core part of nearly any application, especially when that application is a web page. There are many existing solutions to this problem, but too often they make assumptions that don’t work for your application. For example, jQuery Validate has a lot of features but depends on jQuery and is tied to the DOM. For another, joi is promising but it is completely synchronous and has no way to declare validations that apply conditionally or depend on multiple values.

At Square, we use a few different JavaScript frameworks for creating dynamic web applications, the most common being Ember.js and Backbone. These frameworks have significantly different philosophies and any DOM code would be specific to one or the other. Because of this we felt that having a shared library for the core validation functionality would be the preferred way to go. That library should be asynchronous, validate at the object level, allow conditional & multi-property validation, and be completely independent of the DOM.

That library is LGTM*. It can be used in either node.js or the browser. It’s built to support async all the way through. It’s built to validate an object at a time and understands dependencies between properties. It leaves decisions about how to validate, when to validate, and how to display errors in your hands. Here’s a simple example of building a validator:

var validator =
.required("What's your name?")
.email("That's no email!")

Once you have a validator you can validate objects with a callback (validate also returns a promise):

validator.validate({ name: 'Brian', email: 'foo' }, function(err, result) {
console.log(result.valid); // => false
console.log(result.errors.email); // => ["That's no email!"]

For more information on custom validations, multi-property validations, promisesupport, and more please see the wiki. We hope you enjoy using LGTM in your apps, and we hope you contribute back any improvements you make!

*An initialism standing for “looks good to me”.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.