Skip to content

Instantly share code, notes, and snippets.

@Gwash3189
Created June 23, 2015 03:51
Show Gist options
  • Save Gwash3189/da46019bfe6e47b22a1c to your computer and use it in GitHub Desktop.
Save Gwash3189/da46019bfe6e47b22a1c to your computer and use it in GitHub Desktop.
basic fluid validation in coffeescript
class ValidationInstance
constructor: (@item, @rules...) ->
class Validation
flatten = (arr) ->
merged = [];
merged.concat.apply(merged, arr);
_toValidate = null
instances = []
RuleFor: (func) =>
_toValidate = func(@)
@
NotEmpty: () =>
func = (x="") -> x isnt "" and x.length > 0 and x isnt undefined
instances.push(new ValidationInstance(_toValidate, func))
@
GreaterThan: (value) =>
func = (x) -> x > value
instances.push(new ValidationInstance(_toValidate, func))
Validate: () =>
flatten(instances.map((x) => x.rules.map((y)=> y(x.item))))
class UserValidator extends Validation
constructor: (name, number) ->
@RuleFor(() -> name)
.NotEmpty()
@RuleFor(() -> number)
.GreaterThan(5)
class User extends UserValidator
constructor: (name, number) ->
super
u = new User("Name", 5);
console.log(u.Validate())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment