Skip to content

Instantly share code, notes, and snippets.

@IzumiSy
Created August 27, 2017 04:37
Show Gist options
  • Save IzumiSy/f9712b89544920fe1efe6ea964993ee4 to your computer and use it in GitHub Desktop.
Save IzumiSy/f9712b89544920fe1efe6ea964993ee4 to your computer and use it in GitHub Desktop.
Immutable Record with validate.js
//
// 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()));
}
@dedoussis
Copy link

This will not work with multiple Record factories, as only the last specified schema will be mounted on the prototype._validationErrors attribute

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment