Validate Object Shapes with Lodash conforms
Lodash's _.conforms method provides a declarative
approach to data validation by generating a reusable predicate function
based on an object of validator functions. This article explains the
internal mechanics of _.conforms, how it maps validation
logic across individual properties, and how you can use it to
efficiently check complex object shapes and enforce data integrity in
JavaScript applications.
How _.conforms Works
The _.conforms method accepts a source
object where keys match the expected property names of a target object,
and the values are predicate functions (functions that return
true or false).
_.conforms(source)When invoked with this source, _.conforms
returns a new function. When this returned function receives an object
to validate, it iterates over the keys defined in the
source specification. For every key, it passes the target
object's corresponding value to the assigned predicate function.
If every predicate function returns a truthy value, the overall check
returns true. If any predicate returns a falsy value, the
evaluation short-circuits or evaluates to false.
Practical Implementation
Consider a scenario where an application must validate incoming user data before processing:
const _ = require('lodash');
// Define the validation schema using predicate functions
const isAdultUser = _.conforms({
name: (val) => typeof val === 'string' && val.trim().length > 0,
age: (val) => typeof val === 'number' && val >= 18,
roles: (val) => Array.isArray(val) && val.includes('editor'),
metadata: (val) => typeof val === 'object' && val !== null && 'verified' in val
});
// Test objects
const validUser = {
name: 'Alex',
age: 28,
roles: ['user', 'editor'],
metadata: { verified: true },
extraField: 'allowed' // Extra fields are ignored
};
const invalidUser = {
name: 'Sam',
age: 16,
roles: ['editor'],
metadata: { verified: false }
};
console.log(isAdultUser(validUser)); // Output: true
console.log(isAdultUser(invalidUser)); // Output: falseKey Characteristics and Mechanics
- Partial Validation:
_.conformsonly inspects the keys specified in the configuration object. Any additional properties on the target object are ignored, allowing for flexible schema validation. - Missing Properties: If an expected property is
missing from the target object, the predicate function receives
undefined. The predicate must account for this if undefined values are invalid. - Integration with Lodash Iterators: Because
_.conformsproduces a standard predicate(value) => boolean, it integrates seamlessly with collection methods like_.filter,_.find, or nativeArray.prototype.filter:
const users = [validUser, invalidUser];
const editors = users.filter(isAdultUser);- Composability: Because each validator is an
isolated function, complex rules can be broken into modular, testable
units or combined with other Lodash utility functions (such as
_.isString,_.isNumber, or_.inRange) to form concise validation schemas.