Skip to content

validator: introduce experimental node:validator module#62927

Open
sheplu wants to merge 4 commits intonodejs:mainfrom
sheplu:simple-validator
Open

validator: introduce experimental node:validator module#62927
sheplu wants to merge 4 commits intonodejs:mainfrom
sheplu:simple-validator

Conversation

@sheplu
Copy link
Copy Markdown
Member

@sheplu sheplu commented Apr 24, 2026

Note: The purpose of this PR is not to reflect what a fully implemented validator would be able to handle. It is intended to open a discussion on whether it makes sense to continue in this direction before investing further in the surface area, feature set, and edge cases.

Introduces a new experimental built-in module node:validator - a synchronous, JSON-Schema-inspired input validator for simple REST-style payload checks.
Gated behind --no-experimental-validator (on by default, opt-out) and emits an ExperimentalWarning on first require.

The purpose of this PR is not reflecting what a fully implemented validator would be able to handle, but to have a discussion to know if this make sense to continue in this line.

Key Features

  • Schema class: validate and normalize a schema once, reuse for many validations.
  • Supported types: string, number, integer, boolean, object, array, null.
  • Constraints:
    • minLength / maxLength / pattern / enum for strings,
    • minimum / maximum / exclusiveMinimum / exclusiveMaximum / multipleOf for numbers,
    • minItems / maxItems / items for arrays,
    • properties / required / additionalProperties for objects.
  • Non-throwing validation: schema.validate(data) returns a frozen { valid, errors } result; never throws.
  • Machine-readable error codes: 13 codes exposed via the codes export (e.g. INVALID_TYPE, STRING_TOO_SHORT, PATTERN_MISMATCH).
  • Defaults: schema.applyDefaults(data) returns a new object with declared defaults applied (input is not mutated).
  • Schema composition: schema.toJSON() returns a frozen copy of the definition so schemas can be embedded in other schemas.
  • Compile-time validation: invalid schema definitions throw ERR_VALIDATOR_INVALID_SCHEMA at new Schema(...), not at validate time.

Example

Example — validate a user payload

  import { Schema } from 'node:validator';

  const userSchema = new Schema({
    type: 'object',
    required: ['name', 'email'],
    properties: {
      name: { type: 'string', minLength: 1, maxLength: 100 },
      email: { type: 'string', pattern: '^[^@]+@[^@]+$' },
      age: { type: 'integer', minimum: 0, maximum: 150 },
      tags: { type: 'array', items: { type: 'string' }, maxItems: 10 },
    },
  });

  const result = userSchema.validate({
    name: 'Alice',
    email: 'alice@example.com',
    age: 30,
    tags: ['admin'],
  });

  console.log(result.valid);  // true
  console.log(result.errors); // []

Example — apply defaults

import { Schema } from 'node:validator';

const schema = new Schema({
  type: 'object',
  properties: {
    host: { type: 'string', default: 'localhost' },
    port: { type: 'integer', default: 3000 },
  },
});

const config = schema.applyDefaults({});
console.log(config.host); // 'localhost'
console.log(config.port); // 3000

A bit of the chicken/egg with the linter, so I also opened nodejs/core-validate-commit#147 and for now using the node(validator) commit message

@nodejs-github-bot
Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/config
  • @nodejs/loaders
  • @nodejs/startup

@nodejs-github-bot nodejs-github-bot added lib / src Issues and PRs related to general changes in the lib or src directory. needs-ci PRs that need a full CI run. labels Apr 24, 2026
@sheplu sheplu force-pushed the simple-validator branch from b7d3be2 to 6fdf84e Compare April 24, 2026 14:41
@sheplu sheplu changed the title Simple validator Implement basic JS validator Apr 24, 2026
@sheplu sheplu changed the title Implement basic JS validator validator: introduce experimental node:validator module Apr 24, 2026
@sheplu sheplu force-pushed the simple-validator branch from 6fdf84e to 3f99703 Compare April 24, 2026 15:12
@sheplu sheplu force-pushed the simple-validator branch from 3f99703 to 9454350 Compare April 24, 2026 15:18
@sheplu sheplu marked this pull request as ready for review April 24, 2026 15:27
@ljharb
Copy link
Copy Markdown
Member

ljharb commented Apr 24, 2026

Unfortunately JSON Schema doesn't support many of the things that JS apps need to validate - functions, regexes, for some examples, so the generic name "validator" doesn't seem like a good fit if it'd only cover JSON-serializable data.

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 24, 2026

Codecov Report

❌ Patch coverage is 99.35980% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 89.67%. Comparing base (2428030) to head (6766f00).
⚠️ Report is 44 commits behind head on main.

Files with missing lines Patch % Lines
lib/internal/validator/compile.js 98.63% 4 Missing ⚠️
lib/internal/validator/schema.js 99.07% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #62927      +/-   ##
==========================================
+ Coverage   89.63%   89.67%   +0.03%     
==========================================
  Files         706      712       +6     
  Lines      219219   220181     +962     
  Branches    42004    42259     +255     
==========================================
+ Hits       196499   197438     +939     
- Misses      14622    14637      +15     
- Partials     8098     8106       +8     
Files with missing lines Coverage Δ
lib/internal/bootstrap/realm.js 96.22% <100.00%> (+<0.01%) ⬆️
lib/internal/errors.js 97.65% <100.00%> (+<0.01%) ⬆️
lib/internal/process/pre_execution.js 98.28% <100.00%> (-0.11%) ⬇️
lib/internal/validator/defaults.js 100.00% <100.00%> (ø)
lib/internal/validator/errors.js 100.00% <100.00%> (ø)
lib/internal/validator/validate.js 100.00% <100.00%> (ø)
lib/validator.js 100.00% <100.00%> (ø)
src/node_options.cc 76.53% <100.00%> (-0.08%) ⬇️
src/node_options.h 98.00% <100.00%> (+0.01%) ⬆️
lib/internal/validator/schema.js 99.07% <99.07%> (ø)
... and 1 more

... and 48 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Qard
Copy link
Copy Markdown
Member

Qard commented Apr 24, 2026

A bit of overlap with the ata effort in #62603. Might want to just expose that instead given the measured perf.

@mertcanaltin
Copy link
Copy Markdown
Member

mertcanaltin commented Apr 24, 2026

Hey @sheplu, good to see this come up. We've been on the same track.

Context: #62603 is vendoring ata into core for node.config.json right now (two approvals, @lemire as co-author) Once that lands, exposing it to userland is the obvious next thing, and @TheOneTheOnlyJJ and @H4ad both asked for it during that review.

On @ljharb's naming point, agreed, validator reads a bit broad. A few shapes on the table: node:schema, node:jsonschema, or a wider node:json covering parse and validate (ata already vendors simdjson).

Going to open a tracking issue shortly and drop the link here. Syncing with @H4ad later today, happy to pull you in if you want to compare notes.

Appreciate you kicking this off. Rather keep these in sync than run two efforts in parallel.

@sheplu
Copy link
Copy Markdown
Member Author

sheplu commented Apr 24, 2026

Seems like I was bad at searching for something similar! Thanks @Qard

@mertcanaltin definitely, feel free to include me! More that happy to help work on that. And yes the naming was broad :D

@mertcanaltin
Copy link
Copy Markdown
Member

mertcanaltin commented Apr 24, 2026

:D The issue being followed is currently open: #62598, I'm awaiting your comments.

@Qard
Copy link
Copy Markdown
Member

Qard commented Apr 24, 2026

@sheplu No worries. I've just been reviewing it so had it already in my mind when I saw this. I actually assumed at first that this was just going to be the work to expose that, since I knew it had not been done yet. 😅

@Delapouite
Copy link
Copy Markdown
Contributor

I feel like asking input from people who explored this topic along the years would be valuable? Friendly ping to @colinhacks from zod and @ssalbdivad from ArkType who may have a few ideas to share on design of such validation API in Node.

Copy link
Copy Markdown
Member

@mcollina mcollina left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not convinced this belongs to core. The ecosystem is having constant innovation on this area in the last few years, and solidifying something in core like this would hamper it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

lib / src Issues and PRs related to general changes in the lib or src directory. needs-ci PRs that need a full CI run.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants