mikeerickson / validatorjs

A data validation library in JavaScript for the browser and Node.js, inspired by Laravel's Validator.
https://www.npmjs.com/package/validatorjs
MIT License
1.77k stars 280 forks source link

How to add dependent validation rules? #167

Closed zhaoyi0113 closed 7 years ago

zhaoyi0113 commented 7 years ago

I have two form fields and they have a dependency. The second field is required only if the first field value is true. How can I add such dependent validation rules on the second field?

mikeerickson commented 7 years ago

You can use the present rule

// Should fail
new Validator({}, {
  name: 'string|present'
);

// Should fail
new Validator({
  name: []
}, {
  name: 'string|present'
);
zhaoyi0113 commented 7 years ago

Thanks for your answer. It should work. Is there a way for me to place more complex logic on the validation rule for that? Can I inject a function into the rule to do some validate calculation?

mikeerickson commented 7 years ago

@zhaoyi0113 You can create your own rule if you would like to be as verbose as you wish

https://github.com/skaterdav85/validatorjs#registering-custom-validation-rules

If this does not do what you need, let me know and I will have a closer look at what you are trying to do.

zhaoyi0113 commented 7 years ago

Thanks for your help.

mikeerickson commented 7 years ago

@zhaoyi0113 sure thing 👍