npm.io
1.0.0 • Published 3 months ago

@validatem/default-to

Licence
WTFPL OR CC0-1.0
Version
1.0.0
Deps
0
Size
4 kB
Vulns
0
Weekly
0

@validatem/default-to

This validator is designed to be used with Validatem, the universal and composable validation library.

Inserts a default value if one is not given, or passes through the specified value unchanged if it is - but never rejects any value. Typically used for optional values, as the 'opposite' of @validatem/required.

Note that both null and undefined are treated as "no value is given".

License, donations, and other boilerplate

Licensed under either the WTFPL or CC0, at your choice. In practice, that means it's more or less public domain, and you can do whatever you want with it. Giving credit is not required, but still very much appreciated! I'd love to hear from you if this module was useful to you.

Creating and maintaining open-source modules is a lot of work. A donation is also not required, but much appreciated! You can donate here.

Example

A runnable version of this example is included in the repository, as example.js.

"use strict";

const { validateValue } = require("@validatem/core");
const defaultTo = require("@validatem/default-to");

let rules = [
	defaultTo("bar")
];

console.log(validateValue("foo", rules)); // foo
console.log(validateValue(null, rules)); // bar

API

If you are new to Validatem, please read the documentation on the Validatem website first - it will explain how the general API works, and how you should use validator modules with it.

defaultTo(defaultValueOrFunction)

Callable. Either passes through the input value as-is, or if it is null or undefined, inserts the specified defaultValue instead.

You may specify either a default value directly, or specify a function. If you specify a function, then it will be called only if the input was empty and a default value is needed. This is typically useful when generating a default value is computationally expensive, and you only want to do it when necessary. If the default value itself is supposed to be a function, see the literal variant of this function below instead.

  • defaultValueOrFunction: Either a literal value to default to, or a function that returns one.

Possible error codes: None.

defaultTo.literal(defaultValue)

Same as above, except if you pass in a function as the defaultValue, it is used as the default value as-is, and is never called.

Changelog

1.0.0 (July 29, 2026)

Initial (stable) release.

Keywords