クライアント・サーバーでバリデーションの仕組みを共有したい
https://github.com/ishiduca/js-valid
- サーバーとクライアントの両方で同じバリデータとスキーマを使いたい
- 型チェックは既存のライブラリ(お好みの)に任せたほうが楽(な気がする)
例えば、undersocore.js のようなサーバーからもクライアントからも同じリソースを参照できるライブラリがあるので、それ使うことが許される環境なら、スキーマも両方から参照できるところに配置しておけば楽だなーとか。
schema.js
(function (g) { var underscore = g._ ? g._ : (function () { return require('./underscore'); })(); var schema = { foo: underscore.isString , bar: { type: underscore.isString , required: true varidate: /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/ } , count: { type: function isInt (v) { return underscore.isNumber(v) && n === parseInt(n); } , default: 0 } }; if ('undefined' !== typeof module && module.exports && 'function' === typeof require ) { module.exports.schema; } else { // this === window g.schema = schema; } })(this);
app.js
var Validator = require('js-valid').Validator; var underscore = require('./underscore'); var schema = require('./schema'); var validator = new Validator(schema); method({ foo: '100', bar: 'fo.o@bar.org' }); // { foo: '100', bar: 'fo.o@bar.org', count: 0 } method({ foo: '100' }); // Error: RequiredError: "bar" not found function method (query) { var validated; try { validated = validator.validate(query); } catch (e) { console.error(e.name + ': ' + e.message); } return validated; }
クライアントサイドでも同じような呼び出し方出来る
var validator = new some.Validator(schema); ...
、、、と、ここまできたら、通信する際の シリアライズとデシリアライズ機能あると楽ですよね?
+---(クライアント)---+ | | | beforeValidateObj | | | | -+ | [validate] -> エラー処理 | | | | +-- validator.stringify(beforeValidateObj) | afterValidateObj | | | | | | | [serialize] | | | | | -+ | string | +---------+----------+ | HTTP通信 | +-----(サーバー)-----+ | string | | | | -+ | [deserialize] | | | | | +-- validator.parse(string) | deserializedObj | | | | | | | [validate] -> エラー処理 | | | | -+ | afterValidateObj | | | +---------+----------+
、、、この辺の仕組みスマートにやりたいな