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: false

Key Characteristics and Mechanics

const users = [validUser, invalidUser];
const editors = users.filter(isAdultUser);