Created
August 27, 2017 04:37
-
-
Save IzumiSy/f9712b89544920fe1efe6ea964993ee4 to your computer and use it in GitHub Desktop.
Immutable Record with validate.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Example for Immutable Record with validate.js | |
// | |
const _ = require("underscore"); | |
const I = require("immutable"); | |
const validate = require("validate.js"); | |
function ValidatableRecord(args, rules = {}) { | |
const _prototype = I.Record.prototype; | |
_prototype._validationErrors = [] | |
_prototype.validate = function() { | |
_prototype._validationErrors = | |
(validate(this.toJS(), rules, { format: "flat" }) || []); | |
return !!!_prototype._validationErrors.length | |
} | |
_prototype.getErrors = function() { | |
return _prototype._validationErrors; | |
} | |
return I.Record(args); | |
} | |
/* | |
* Usage | |
*/ | |
const ManRecord = ValidatableRecord({ name: null }, { | |
name: { | |
presence: true, | |
length: { | |
maximum: 4 | |
} | |
} | |
}); | |
const man = new ManRecord({ name: "Justine" }); | |
if (!man.validate()) { | |
console.log(_.first(man.getErrors())); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will not work with multiple Record factories, as only the last specified schema will be mounted on the
prototype._validationErrors
attribute