Created
August 25, 2014 16:14
-
-
Save evillemez/cbde6b26f0bafe72f41a to your computer and use it in GitHub Desktop.
An API for validation that I would like...
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
#empty validator | |
validator = new Validator() | |
#custom app validator | |
validator.constraint 'unique-name', (val, ops = {}) -> | |
namelist = [] #... array of names in system | |
return "Name already exists!" if namelist.indexOf val > -1 | |
return true | |
#another custom validator | |
validator.constraint 'phone-number', (val, ops = {}) -> | |
#... custom phone number validation | |
return true | |
#define schema for object | |
validator.schema 'user' | |
.prop 'firstName' | |
.constrain 'type', 'string' | |
.constrain 'required' | |
.constrain 'unique-name' | |
.prop 'email', | |
.constrain 'email' | |
.constrain 'required' | |
.prop 'mailingAddress' | |
.constrain 'schema', 'address' | |
.prop 'phone' | |
.constrain 'phone-number' | |
.prop 'previousAddresses' | |
.constrain 'type', 'array' | |
.constrain 'length', min: 1 | |
.constrain 'each', name: 'schema', options: 'address' | |
#schema for nested object, the "schema" constraint means apply this schema to a sub-object | |
validator.schema 'address' | |
.constrain 'us-address' #constraint can be on entire object, or specific property | |
.prop 'street' | |
.constrain 'required' | |
.prop 'city' | |
.constrain 'required' | |
.prop 'areaCode' | |
.constrain 'required' | |
#an structure to validate | |
user = | |
firstName: "Foobert" | |
email: '[email protected]' | |
phone: '333-333-3333' | |
primaryAddress: | |
street: 'foo' | |
city: 'bar' | |
areaCode: 90210 | |
previousAddresses: [ | |
{street: '1828 L ST NW', city: 'Anytown', areaCode: 44455} | |
{street: '1828 L ST NW', city: 'Anytown', areaCode: 44455} | |
] | |
# would throw an error if a constraint returns a promise | |
errors = validator.validate 'user', user | |
# will return already resolved promise if nothing was actually async | |
promise = validator.validateAsync 'user', user | |
promise.then (errors) -> | |
#do stuff | |
#use a specific validator on a specific value | |
errors = validator.validateValue '333-456-2435', 'phone-number', {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment