JavaScript对象校验:legalize.js
legalize.js 是 PayPal 用来执行对象验证的库。
Legalize.js is a library that performs validation of domain objects. It does not perform validation of web forms. It is optimized for the browser but can as well be used on the server side in a NodeJS environment.
Build
npm install grunt build
will build the library indist/legalize.min.js. It is around 7KB minified and 3KB minified+gzipped.
npm check
will execute unit tests and check code coverage (report will be genereated incoverage/lcov-report/index.html). The accepted threshold is ≥ 90%.
Use it in the browser <script src="legalize.min.js"></script> <script> var validationResult = Legalize.validate("given.something", Legalize.string().url()); </script>
Use it using require.js
The library has an AMD (asynchronous module definition), so it works with AMD loaders such as require.js.
Use it in NodeJS var Legalize = require("legalize"); var validationResult = Legalize.validate(Math.PI, Legalize.number().integer());
Quick Tutorial
Legalize basically consists ofLegalize.validateand a bunch of schema builders. You validate a value against a schema and in return you get an object with the legalized value, error and warnings messages (if there are any).
Here is how you could validate an object:
var personSchema = { 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(), }; var validationResult = Legalize.validate({ firstName: "Alexander", lastName: "Carnicero", age: 27 }, personSchema); if (validationResult.error) { // report error here } else { validationResult.warnings.forEach(function (warning) { // report warning }); // validationResult.value contains validated value }