Re-usable validation, with optional() and exists()
See original GitHub issueI have a user route where one can POST (to create a user) or PUT (to edit a user). A user has a username that I want to validate.
In the POST case I want to validate that it exists() In the PUT route I want to validate that it is optional()
But in both routes I want to validate that the username fulfills this part, which I want to re-use:
.isLength({ min: 1, max: 20 })
.matches(/^[a-zA-Z0-9][a-zA-Z0-9-_]*$/)
.withMessage('Username can only contain a-zA-Z0-9-_')
I do not know how to achieve this, with re-usability, considering the .optional()
and .exists()
should come first in those two validation chains.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:10 (5 by maintainers)
Top Results From Across the Web
Validating Optional Objects with Yup - Object Partners
The Yup object validation library provides a lot of tools, but how do we use it to validate optional objects?
Read more >How to Create an Optional Dynamic Validation Schema based ...
In this lesson we'll show how to setup a nested validation structure ... We'll make our nested validation optional only if our `optionalObject`...
Read more >How to make input validation simple and clean in ... - Medium
Let's create a middleware function validate() in our /controllers/user.js : ... As you can see, for a required field we are using the...
Read more >Apply "exists" validation for optional field in Laravel
// Define validation rules $validator = Validator::make($request->all(), [ 'user_group_id' => 'sometimes|exists:groups,id', ' ...
Read more >Custom Validators — FluentValidation documentation
There are several ways to create a custom, reusable validator. The recommended way is to make use of the Predicate Validator to write...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
This is something we should definitely implement because the same problem also happened to me. You may resolve with some kind of wrapper around
checkSchema
. (Keep also in mind that if you want to edit partially an entity you should use PATCH instead of PUT.) /cc @gustavohenkeDoes this solve the issue for you @jatinmehrotra?