Struct level validations

Validations can also be registered at the struct level when field level validations
don’t make much sense. This can also be used to solve cross-field validation elegantly.
Additionally, it can be combined with tag validations. Struct Level validations run after
the structs tag validations.

Example requests

  1. # Validation errors are generated for struct tags as well as at the struct level
  2. $ curl -s -X POST http://localhost:8085/user \
  3. -H 'content-type: application/json' \
  4. -d '{}' | jq
  5. {
  6. "error": "Key: 'User.Email' Error:Field validation for 'Email' failed on the 'required' tag\nKey: 'User.FirstName' Error:Field validation for 'FirstName' failed on the 'fnameorlname' tag\nKey: 'User.LastName' Error:Field validation for 'LastName' failed on the 'fnameorlname' tag",
  7. "message": "User validation failed!"
  8. }
  9. # Validation fails at the struct level because neither first name nor last name are present
  10. $ curl -s -X POST http://localhost:8085/user \
  11. -H 'content-type: application/json' \
  12. -d '{"email": "george@vandaley.com"}' | jq
  13. {
  14. "error": "Key: 'User.FirstName' Error:Field validation for 'FirstName' failed on the 'fnameorlname' tag\nKey: 'User.LastName' Error:Field validation for 'LastName' failed on the 'fnameorlname' tag",
  15. "message": "User validation failed!"
  16. }
  17. # No validation errors when either first name or last name is present
  18. $ curl -X POST http://localhost:8085/user \
  19. -H 'content-type: application/json' \
  20. -d '{"fname": "George", "email": "george@vandaley.com"}'
  21. {"message":"User validation successful."}
  22. $ curl -X POST http://localhost:8085/user \
  23. -H 'content-type: application/json' \
  24. -d '{"lname": "Contanza", "email": "george@vandaley.com"}'
  25. {"message":"User validation successful."}
  26. $ curl -X POST http://localhost:8085/user \
  27. -H 'content-type: application/json' \
  28. -d '{"fname": "George", "lname": "Costanza", "email": "george@vandaley.com"}'
  29. {"message":"User validation successful."}