"Required if" custom validator
See original GitHub issueHi! I’m trying to achieve a “required if” behavior using a custom validator. But since .optional()
disables the validators when the value is not provided, the custom validator is never called. Is there any way to force it to be called or can I programmatically call other validators in my custom validator?
I’m using version 5.3.0.
Sample code
const express = require('express')
const { body, validationResult } = require('express-validator/check')
const app = express()
app.use(express.urlencoded({ extended: true }))
app.post('/',
body('url')
.custom((value, { req }) => {
console.log('I\'m never called when .optional() is set :(')
if (req.body.param && !value) {
throw new Error('url is required if "param" was provided');
}
// can I call `.isURL()` here, so I can skip the `.optional()`?
return true
})
.optional()
.isURL().withMessage('Invalid URL'),
body('param').optional(),
(req, res) => {
res.send(validationResult(req).array())
});
app.listen(3000)
Thanks!
Issue Analytics
- State:
- Created 5 years ago
- Comments:6
Top Results From Across the Web
3 ways to implement conditional validation of Angular reactive ...
If checkbox value is true , we will set the required validator to myEmailField . ... Workaround #2: create custom conditional group validator....
Read more >asp.net mvc 3 - RequiredIf Conditional Validation Attribute
custom validation attribute. It compares against a single other property value but you could easily tweak the IsValid method to meet your ......
Read more >The best way to implement custom validators - Angular inDepth
To validate required fields, for example, we can use the built-in required validator on template-driven forms by adding the required attribute. const control...
Read more >Angular Custom Form Validators: Complete Guide
a custom validator is a function that validates the value of a form field according to a business rule, such as form example...
Read more >How To Use Custom Form Validation in Angular - DigitalOcean
Validators are used to ensure that the values in a form meet certain requirements. They are available to Template-Driven Forms or Reactive Forms ......
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
Thanks! I haven’t thought about it. This totally worked!
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.