Skip validations if a field is not required
See original GitHub issueIs your feature request related to a problem? Please describe. I have registered an optional text field with several validators. I think the validators should not run if the field is empty, because it’s optional, and an empty optional field is by definition valid.
The sandbox illustrates just one validation for simplicity.
Describe the solution you’d like
If a field is empty and it was registered with required: false
or without required
specified, then skip running the validate
functions.
Logical reasoning:
Here are all 6 combinations of a field (empty vs. non-empty) and required
(true, false, undefined):
- field empty
- (1) required: true -> error already, no need to run validators
- (2) required: false -> no error, no need to run validators because there’s nothing to validate
- (3) required not specified -> no error, no need to run validators because there’s nothing to validate
- field non-empty
- (4) required: true -> no error yet, run validators for further validation
- (5) required: false -> no error yet, run validators for further validation
- (6) required not specified: no error yet, run validators for further validation
My proposal is to not run validators in cases (2) and (3). Validators should be run in all other cases.
The only exception I can think of for cases (2) and (3) is if the field has a validator that checks for content (minimum length, regexp match etc.), but that means the field should have been declared with { required: true }
in the first place, which falls under cases (1) or (4), and validators should be run in those cases.
Describe alternatives you’ve considered
Currently, I have to prefix each validator to return true if the field value is empty:
validate: {
rule1: value => value === '' || actualValidationLogic(value) || message;
rule2(value) {
if (value === '')
return true;
// ... actual validation logic
}
...
}
This is redundant and inelegant.
Additional context
Benefits of adopting this proposal
- Cleaner code. Validators no longer need to check for empty values.
- Faster validation for empty non-required fields by skipping validation altogether.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:33
- Comments:36 (23 by maintainers)
I got the solution @bluebill1049, I am realize that yup object is promise(), so if i place .min(), it’s still run the validation. So i use this solution like this. here is the codeSanbox link: https://codesandbox.io/s/boring-ramanujan-q3c54?file=/src/App.js
Is this feature added ? i also want Skip validations if a field is not required