At the moment, our existing code still uses custom-defined if statements to validate the email and password fields of the Create User request payload object. Since we will be using a JSON Schema validation library for our profile object, we should also migrate our existing validation logic to a JSON Schema to remain consistent. Therefore, let's create a schema for the entire Create User request payload object.
Create a new file at src/schema/users/create.json, and insert the following schema:
{
"$schema": "http://json-schema.org/schema#",
"$id": "http://api.hobnob.social/schemas/users/create.json",
"title": "Create User Schema",
"description": "For validating client-provided create user object",
"type": "object",
"properties": {
"email": {
"type": "string",
"format": "email"
},
"password": { "type": "string" },
"profile": { "$ref": "profile.json#"}
},
"required": ["email", "password"],
"additionalProperties": false
}
There are a few things to note here:
- We are using the format property to ensure that the email property is a valid email, as defined by RFC 5322, section 3.4.1 (https://tools.ietf.org/html/rfc5322#section-3.4.1). However, we also want to exclude certain syntactically-valid emails like daniel@127.0.0.1, which are likely to be spam. Later in this chapter, we will show you how to override this default format.
- We have used a JSON reference ($ref) to reference the profile schema we defined earlier. The $ref syntax was specified in https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 and allows us to compose more complex schema from existing ones, removing the need for duplication.
- We have marked the email and password properties as required.