-
-
Save glenjamin/1214146 to your computer and use it in GitHub Desktop.
which is the nicer validation syntax?
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
// What's the best syntax to validate a JSON object? | |
var addr = { NamePrefixText: "Dr.", FirstName: "Lex", LastName: "Luthor", | |
Address: ["5 Upper Ter"], CityName: "SF" }; | |
Validate(addr, Address); // returns true if valid, errors go in an error object like AR | |
// Here are some possibilities: | |
// implicit type | |
var Address = { | |
NamePrefixText : Valid.oneOf("", "Mr.", "Mrs.", "Ms.", "Dr."), | |
FirstName : Valid.nonBlank(), | |
MiddleName : Valid.string().optional(), | |
LastName : Valid.nonBlank(), | |
Address : Valid.length(1,2).arrayOf(Valid().string()), | |
CityName : Valid.nonBlank(), | |
}; | |
// explicit type passed to constructor | |
var Address = { | |
NamePrefixText : Valid('string').oneOf("", "Mr.", "Mrs.", "Ms.", "Dr."), | |
FirstName : Valid('string').nonBlank(), | |
MiddleName : Valid('string').optional(), | |
LastName : Valid('string').nonBlank(), | |
Address : Valid('array').length(0,2).arrayOf(Valid().string()), | |
CityName : Valid('string').nonBlank(), | |
}; | |
// explict type chained | |
var Address = { | |
NamePrefixText : Valid.string().oneOf("", "Mr.", "Mrs.", "Ms.", "Dr."), | |
FirstName : Valid.string().nonBlank(), | |
MiddleName : Valid.string().optional(), | |
LastName : Valid.string().nonBlank(), | |
Address : Valid.array(Valid().string()).length(1,2) | |
CityName : Valid.string().nonBlank(), | |
}; | |
// function objects (current scheme, ugh) | |
var Address = { | |
NamePrefixText : Val.IsOneOf("", "Mr.", "Mrs.", "Ms.", "Dr."), | |
FirstName : Val.IsNonBlankString, | |
MiddleName : Val.IsString, | |
LastName : Val.IsNonBlankString, | |
Address : Val.IsArray(IsString, {min: 1, max : 2}), | |
CityName : Val.IsNonBlankString, | |
}; | |
// Block function magic | |
var Schema = validate.define(function(v) { | |
v('NamePrefixText').is(v.string, v.nonEmpty, v.oneOf("a", "b", "c")); | |
v('FirstName').is(v.string, v.nonEmpty); | |
}); | |
validate(object, Schema); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment