JavaScript對象校驗:legalize.js

jopen 9年前發布 | 11K 次閱讀 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
}

項目主頁:http://www.baiduhome.net/lib/view/home/1427787483178

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!