Custom Validations
You can also define custom validation logic for your fields. Let’s add a custom validation to the title
field to ensure it is longer than 2 characters.
Code Explanation
- We added a custom validation function to the
title
field using thevalidate
option. - The custom validation function checks if the
title
field’s length is greater than 2. If the condition is not met, it returns the error message'too short'
. - We specified the
Task
type in the generic definition ofFields.string<Task>
, which provides type safety and ensures the custom validation function receives the correct type. - This arrow function will run both on the frontend as frontend validation and on the backend as API validation, ensuring consistent validation across the stack.
Try It Out
Try adding tasks with titles shorter than 3 characters to see the custom validation in action. The error message 'too short'
will be returned if the validation fails.
Files
Preparing Environment
- Installing dependencies
- Starting http server