Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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);
Add Comment
Please, Sign In to add comment