Guest User

Untitled

a guest
Jan 22nd, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. // What's the best syntax to validate a JSON object?
  2. var addr = { NamePrefixText: "Dr.", FirstName: "Lex", LastName: "Luthor",
  3. Address: ["5 Upper Ter"], CityName: "SF" };
  4. Validate(addr, Address); // returns true if valid, errors go in an error object like AR
  5.  
  6.  
  7. // Here are some possibilities:
  8.  
  9. // implicit type
  10. var Address = {
  11. NamePrefixText : Valid.oneOf("", "Mr.", "Mrs.", "Ms.", "Dr."),
  12. FirstName : Valid.nonBlank(),
  13. MiddleName : Valid.string().optional(),
  14. LastName : Valid.nonBlank(),
  15. Address : Valid.length(1,2).arrayOf(Valid().string()),
  16. CityName : Valid.nonBlank(),
  17. };
  18.  
  19.  
  20. // explicit type passed to constructor
  21. var Address = {
  22. NamePrefixText : Valid('string').oneOf("", "Mr.", "Mrs.", "Ms.", "Dr."),
  23. FirstName : Valid('string').nonBlank(),
  24. MiddleName : Valid('string').optional(),
  25. LastName : Valid('string').nonBlank(),
  26. Address : Valid('array').length(0,2).arrayOf(Valid().string()),
  27. CityName : Valid('string').nonBlank(),
  28. };
  29.  
  30.  
  31. // explict type chained
  32. var Address = {
  33. NamePrefixText : Valid.string().oneOf("", "Mr.", "Mrs.", "Ms.", "Dr."),
  34. FirstName : Valid.string().nonBlank(),
  35. MiddleName : Valid.string().optional(),
  36. LastName : Valid.string().nonBlank(),
  37. Address : Valid.array(Valid().string()).length(1,2)
  38. CityName : Valid.string().nonBlank(),
  39. };
  40.  
  41.  
  42. // function objects (current scheme, ugh)
  43. var Address = {
  44. NamePrefixText : Val.IsOneOf("", "Mr.", "Mrs.", "Ms.", "Dr."),
  45. FirstName : Val.IsNonBlankString,
  46. MiddleName : Val.IsString,
  47. LastName : Val.IsNonBlankString,
  48. Address : Val.IsArray(IsString, {min: 1, max : 2}),
  49. CityName : Val.IsNonBlankString,
  50. };
  51.  
  52.  
  53. // Block function magic
  54. var Schema = validate.define(function(v) {
  55. v('NamePrefixText').is(v.string, v.nonEmpty, v.oneOf("a", "b", "c"));
  56. v('FirstName').is(v.string, v.nonEmpty);
  57. });
  58.  
  59. validate(object, Schema);
Add Comment
Please, Sign In to add comment