Legalize.js

Legalize.validate(Math.PI, Legalize.number().integer());

{
  "error": [
    {
      "type": "checks_failed",
      "sourcePath": "",
      "sourceValue": 3.141592653589793
    }
  ],
  "warnings": null
}

A more complex schema

var schema = {
    firstName:
        Legalize.string().minLength(1).maxLength(30).required(),
    lastName:
        Legalize.string().minLength(1).maxLength(30).required(),
    age:
        Legalize.number().integer().min(18),
    sex:
        Legalize.string().sanitizeBefore(function (value) {
                value.toLowerCase();
        }).valid("male", "female").optional(),
};

This is an ordinary validation against the above schema which succeeds:

Legalize.validate({ firstName: "Alexander", lastName: "Carnicero", age: 27 }, schema);

{
  "error": null,
  "value": {
    "firstName": "Alexander",
    "lastName": "Carnicero",
    "age": 27
  },
  "warnings": null
}

This validation will issue a warning, since age does not fulfill the constraint, but it is also not required (if it was, the validation would fail with an error). If you want invalid options to issue warnings true, you can specify the option warnOnInvalidOptionals: false (see below).

Legalize.validate({ firstName: "Alexander", lastName: "Carnicero", age: 10 }, schema);

{
  "error": null,
  "value": {
    "firstName": "Alexander",
    "lastName": "Carnicero"
  },
  "warnings": [
    {
      "type": "checks_failed",
      "sourcePath": "/age",
      "sourceValue": 10
    }
  ]
}

Here warnOnInvalidOptionals: false is specified (otherwise it defaults to true), so the given optional but invalid value will make the validation fail.

Legalize.validate({ firstName: "Alexander", lastName: "Carnicero", age: 10 }, schema);

{
  "error": [
    {
      "type": "checks_failed",
      "sourcePath": "/age",
      "sourceValue": 10
    }
  ],
  "value": {
    "firstName": "Alexander",
    "lastName": "Carnicero"
  },
  "warnings": null
}
Fork me on GitHub