Created
June 23, 2015 03:51
-
-
Save Gwash3189/da46019bfe6e47b22a1c to your computer and use it in GitHub Desktop.
basic fluid validation in coffeescript
This file contains 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
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