1.0.0 • Published 7 years ago

vtypes-requiredif v1.0.0

Weekly downloads
2
License
MIT
Repository
github
Last release
7 years ago

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

nametypedefaultdescription
attributestringThe attribute key that you want to check
attributeValuestringWhen set, the value of the attribute should equal to this
comparatorfunctioncustom comparison method. In the event target value is of a complex type
messagestringis required when %{attribute} is presentError message
symbolForAnystring*symbol to use when no attributeValue is defined
truthybooleanfalseChecks for truthy values instead of checking only for null and undefined values

License

vtypes-requiredif is MIT licensed