vtypes-requiredif

1.0.0 • Public • Published

vtypes-requiredif

"Required If" validator for validate.js

npm package vtypes

About

The requiredIf validator attempts to ensure that the input is present and not empty when another field is present / equal to any predefined value.

Installation

Using npm:

$ npm i --save vtypes-requiredif
const validate = require('validate.js');
const requiredIf = require('vtypes-requiredif');

// you can then proceed to register the required validators.
validate.validators.requiredIf = requiredIf;

Usage

const constraint1 = {
  attr: {
    requiredIf: {attribute: 'other'}
  }
}

validate({}, constraint1);
// => undefined

validate({other: 'bar'}, constraint1);
// => {attr: ['Attr is required when other is present and equal to *']}

validate({attr: 'foo', other: 'bar'}, constraint1);
// => undefined

const constraints2 = {
  attr: {
    requiredIf: {attribute: 'other', attributeValue: 'bar2'}
  }
}

validate({other: 'bar2'}, constraints2);
// => {attr: ['Attr is required when other is present and equal to *']}

validate({attr: 'foo' other: 'bar2'}, constraints2);
// => undefined

For more examples, check out the test files in this package's source folder.

Available Options

name type default description
attribute string The attribute key that you want to check
attributeValue string When set, the value of the attribute should equal to this
comparator function custom comparison method. In the event target value is of a complex type
message string is required when %{attribute} is present Error message
symbolForAny string * symbol to use when no attributeValue is defined
truthy boolean false Checks for truthy values instead of checking only for null and undefined values

License

vtypes-requiredif is MIT licensed

Package Sidebar

Install

npm i vtypes-requiredif

Weekly Downloads

1

Version

1.0.0

License

MIT

Last publish

Collaborators

  • geraldyeo