Notorious Penguin Magicians


    0.0.3 • Public • Published


    The JSON Object Validator

    What is this?

    Straints is JSON object validator that can be used both in node and in the browser. Validation constraints are declaratively defined in a single JSON or YAML file.

    For example:

          - { method: "isNull", flip: true }
          - { method: "isNull", flip: true }
          - { method: "isEmail" }

    With the above (YAML) configuration, executing a Straints validation with a 'create_user' context will ensure that a JSON object has non-null name and email properties and that email is in a valid format.

    In essence, the goal of this project is to provide an easy way to maintain site-wide validations used on both the client and server in a single place.

    Validation tests are not in the scope of this project, and Straints uses validator.js as its validator by default. You can also configure an alternative validator (See Validators section).

    Awesome. How do I get it?


    npm install straints

    or, as a dependency in your project

    npm install straints --save


    bower install straints

    or, as a dependency in your project

    bower install straints --save

    What's the Setup?

    For Node/Express

    var straints = require('straints');
    straints.configure({ ... });

    With no configuration options specified Straints will look for a validation.json file at the root of your project.

    The app.use() call simply adds the Straints instance to the request object. So, in your controllers you can do

    req.straints.validate(req.body, "create_user", function(results)
        if (results.isValid())
            // all validations passed

    To get at the 'global' instance provided through straints.usage, use


    You can also create a new Straints instance if you need to (and pass config options as necessary).

    straints.newInstance({ ... })

    For the Browser

    You will find the js for the browser in the /dist folder.

    <script src="/path/to/straints/straints.min.js"></script>

    Or, if you wish to use the default validator:

    <script src="/path/to/straints/straints-with-validator.min.js"></script>

    Then you can do

        var instance = StraintsFactory.configure({ ... }).getInstance();    

    With no configuration options specified Straints will simply try to request /validation.json.

    Note that The methods described in For Node/Express are available on StraintsFactory.

    How does all this work?

    Configuration Options

    Here are the config options listed with their defaults.

    • load ('[project-root|http-root]/validation.json')
      Specify the validation configuration data here. Here are the options:

      1. (string)
        In a browser this is assumed to be a URL and an XHR GET is attempted. Otherwise, it will assume this is a filename.
      2. (function)
        Must be of the form
      { load: function(callback) { callback(vcdata); } }

      You can use one of the helper functions for this.

      { load: straints.fileLoader(filename) }
      { load: straints.httpLoader(url) }
      1. (object)
        The JSON VC data itself.
    • datatype ('json')
      The type of data being loaded, when load is a string or function ('yaml' or 'json')

    • validator (validator)
      Specify the test method implementation to use here (See Validators section).

    • useStrings (true)
      Set to true to have values converted to strings prior to validation (necessary for validator.js).

    • log (null)
      There is some logging available. Specify the log function here.

    Validation Configuration (VC)

    Let's start with an example:

          - "others.isNotNull"
          - "others.isNotNull"
          - "isEmail"
        include: "default"
            - "others.isNotNull"
            - "others.isNotNull"
            - "others.isLongStory"
            - ""
            - { method: "isLength", params: { min: 8, max: 16 } }
      - { name: "isNotNull", method: "isNull", flip: true }
      - { name: "isLongStory", method: "isLength", params: { min: 3000 } }


    A 'context' defines a set of constraints to be executed and is identified by having constrain and/or include children. In the example above, the contexts are 'default', 'forms.contact_form', and 'forms.create_user'.


    The context child constrain defines constraints by property name. These constraints will be required if the context is included in the validation session.


    A context can include other contexts by listing their names in an array or comma-delimited string. In the above example, the 'contact_form' context includes 'default', which means all validations in 'default' (and those from contexts it may include, ad infinitum) will also be required when 'contact_form' is used in a validation session.


    Constraints can be defined anywhere in the VC, but wherever they appear they must be in an array. There are 3 ways to specify a constraint in the VC.

    1. Constraint Methods

    The simplest way, is to specify the name of a test method in the validator implementation.

      - "isEmail"

    Note that if the test method requires parameters you will need to build a constraint object instead.

    2. Constraint Object

    This is an actual definition of a constraint. Its unique identifier is the path to it in the VC.

      - { name: "isLongStory", method: "isLength", params: { min: 3000 } }

    Define constraint objects using these attributes:

    • method (string)
      The method on the validator object that will be called.

    • name (string)
      Identifies the constraint within the list. If not specified, method will be used. If more than one constraint have the same identifier within the same list only the first one loaded will be used.

    • params (array)
      An array of additional parameters to be passed to method on validation (for a single parameter brackets are not needed).

    • flip (boolean)
      Set to true to reverse the boolean value returned by method.

    3. Constraint References

    Lastly, you can include an individual constraint by specify the path to it in the VC.

      - "others.isNotNull"

    You can also include an entire array of constraints.

      - ""

    Running a Validation

    straints.validate(target, contexts, complete, validate)
    • target (object)
      The object to be validated

    • contexts (string or array)
      One or more contexts to be validated against

    • complete (function(results))
      Called when validation has completed

      • results (object)
        See Validation Results section below.
    • validate (boolean <= function(property, target, constraint, result))
      Called for every constraint test during the validation session

      • property (string)
        name of the property that was evaludated
      • target (object)
        the object under validation
      • constraint (object)
        validation test that was run
      • result (boolean)
        validation result
      • returns (boolean) the final validation result

    Validation Results

    Here's the rundown on the information available in the validation results object.

    • target
      The JS or JSON object that validation was run against.

    • contexts
      The contexts specified for the validation session.

    • tried
      For each property, the identifiers of the executed constraint tests on the property.

    • failed
      For each property, the identifiers of the failed constraint tests on the property.

    • constraints
      The constraints involved in the validation session indexed by their identifiers.

    • isValid
      A convenience function to determine whether or not all validations passed.


    Straints is bundled with validator.js and uses it by default (i.e., no validator is provided in the configuration).

    You may use any other validator implementation you wish. Just note that Straints will pass the test value as the first argument to the test method, followed by any parameters.

    What Else?


    Check out the changelog.


    Under construction, but what there is of it can be invoked with

    node test




    Happy Validating!


    npm i straints@0.0.3





    Last publish


    • captison