Data Validation
Rejecting bad user data
Rejecting bad user data
Sometimes our users provide bad data

In these cases, we need to provide sensible feedback with a 400 status code.
We always need to handle strings.
Via search parameters in the URL like
/mypage?anything=string.
| |
Via named groups in the URL like
/users/string.
| |
Via form data in POST requests.
| |
HTTP only provides us with strings.
It is the responsibility of the controller to decide how to respond to the incoming request.
| |
If the request contains invalid data, we need to present the user with feedback.
Our solution will rely on data structures we define which describe the constraints we want to impose on our user data.
| |
the validators are simple functions which we can define.
Our validator functions detect errors and return error messages.
A simple required function detects whether we have an empty string.
| |
We can check if the provided string makes a valid Date object
| |
We can use closures to return a function for any minimum (or maximum) length.
| |
Returning nothing (undefined) means validation passed.
In our schema, each field can be given many validator functions.
Validating a field, the first error message is returned or we implicitly return
undefined.
| |
Validating our
formDataagainst an entireschemais a bit more complex. Relying onObject.entriesandObject.fromEntriesto convert our schema object into an array and back to an object.
| |
The validateSchema function can be expanded to provide whatever data we need.
To be really useful, our
validateSchemafunction needs to return more information. We can addisValidboolean andvalidateddata.
| |
Notice that ONLY fields which are present in the schema are being considered. If the user provides additional fields, they are ignored.
It is the responsibility of the controller to decide how to respond to the incoming request.
| |
If the request contains invalid data, we need to present the user with feedback.
The form integrates errors using optional chaining.
| |
Use the CSS :empty pseudoclass to set the error messages to display: none when no message is provided.
If you have any questions, now is a good time to ask.
Thanks for listening