Skip to content

Commit 7eca388

Browse files
committed
[Docs] Add instructions on the required rule JSON pointer
See #356
1 parent 70dbdb0 commit 7eca388

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

docs/basics/validators.md

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -788,6 +788,95 @@ return [
788788
];
789789
```
790790

791+
## Required Rule
792+
793+
Using the required rule can result in a JSON API error object with a JSON pointer to either `/data` or the
794+
actual field that is required, e.g. `/data/attributes/content`. This will vary based on whether the client
795+
omits the field or sends an empty value for the field.
796+
797+
If you always want the pointer to relate to the actual field, e.g. `/data/attributes/content`, ensure
798+
your client *always* sends a value for the field, even if that value is empty (e.g. `null`).
799+
800+
To illustrate this, here are two requests that fail the required rule and the resulting error response:
801+
802+
### Field Omitted
803+
804+
```http
805+
POST /api/posts HTTP/1.1
806+
Content-Type: application/vnd.api+json
807+
Accept: application/vnd.api+json
808+
809+
{
810+
"data": {
811+
"type": "posts",
812+
"attributes": {
813+
"title": "Hello World"
814+
}
815+
}
816+
}
817+
```
818+
819+
```http
820+
HTTP/1.1 422 Unprocessable Entity
821+
Content-Type: application/vnd.api+json
822+
823+
{
824+
"errors": [
825+
{
826+
"status": "422",
827+
"title": "Unprocessable Entity",
828+
"detail": "The content field is required.",
829+
"source": {
830+
"pointer": "/data"
831+
}
832+
}
833+
]
834+
}
835+
```
836+
837+
In this scenario, a JSON pointer of `/data/attributes/content` cannot be used as it would point at a field
838+
that does not exist in the request JSON. Instead, the `/data` pointer indicates the error is caused by the
839+
resource object held in the top-level `data` member.
840+
841+
### Field Empty
842+
843+
```http
844+
POST /api/posts HTTP/1.1
845+
Content-Type: application/vnd.api+json
846+
Accept: application/vnd.api+json
847+
848+
{
849+
"data": {
850+
"type": "posts",
851+
"attributes": {
852+
"title": "Hello World",
853+
"content": null
854+
}
855+
}
856+
}
857+
```
858+
859+
```http
860+
HTTP/1.1 422 Unprocessable Entity
861+
Content-Type: application/vnd.api+json
862+
863+
{
864+
"errors": [
865+
{
866+
"status": "422",
867+
"title": "Unprocessable Entity",
868+
"detail": "The content field is required.",
869+
"source": {
870+
"pointer": "/data/attributes/content"
871+
}
872+
}
873+
]
874+
}
875+
```
876+
877+
In this scenario, the pointer can be `/data/attributes/content` as the field actually exists in the request
878+
JSON.
879+
791880
## Confirmed Rule
792881

793882
Laravel's `confirmed` rule expects there to be a field with the same name and `_confirmation` on the end: i.e.

0 commit comments

Comments
 (0)