1.0.0 • Published 7 years ago

vtypes-requiredunless v1.0.0

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

vtypes-requiredunless

"Required Unless" validator for validate.js

npm package vtypes

About

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

Installation

Using npm:

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

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

Usage

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

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

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

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

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

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

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

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-requiredunless is MIT licensed