Skip to content
Build a serviceDocs 1.3.x

Validation ​

Inventory should receive a meaningful SKU and a positive quantity. Put those rules beside the fields in your protobuf contract; the configured validation interceptor checks it before the handler runs.

Two rules ​

With buf/validate/validate.proto imported:

Proto-first validation

Try the rules

Set quantity to 0, then fix it. The error comes from the rule beside the field.

inventory.proto

proto
message CheckStockRequest {
  string sku = 1 [
    (buf.validate.field).string = {
      min_len: 1
    }
  ];
  int32 quantity = 2 [
    (buf.validate.field).int32 = {
      gt: 0
    }
  ];
}

The generated descriptor carries both rules. Protovalidate reads them on every edit.

CheckStockRequest

Try A-1, an empty value or UNKNOWN.

A whole number. Try 2 → 0 → 2.

Valid request

The request passes validation. The example inventory has 7 units of A-1.

Proto validation
Passed
Example handler
Called locally

{"units":7}

Static successful example. Editing requires JavaScript.

Runs in your browser with @bufbuild/protovalidate and the example handler. No RPC is sent. The handler looks up the SKU in a small inventory fixture.

Compare example inputs

Known SKU · OK

The request passes validation. The handler looks up A-1 in the example inventory and returns its stock.

json
{
  "sku": "A-1",
  "quantity": 2
}
json
{
  "units": 7
}

Zero quantity · InvalidArgument

Zero violates int32.gt. Validation rejects the request before the handler runs.

json
{
  "sku": "A-1",
  "quantity": 0
}
json
{
  "code": "InvalidArgument",
  "issues": [
    {
      "field": "quantity",
      "rule": "int32.gt",
      "message": "must be greater than 0"
    }
  ],
  "message": "The proto rules reject this request. The handler does not run."
}

Empty SKU · InvalidArgument

The empty string violates the proto constraint. Validation rejects the request before the handler runs.

json
{
  "sku": "",
  "quantity": 2
}
json
{
  "code": "InvalidArgument",
  "issues": [
    {
      "field": "sku",
      "rule": "string.min_len",
      "message": "must be at least 1 characters"
    }
  ],
  "message": "The proto rules reject this request. The handler does not run."
}

Unknown SKU · NotFound

The non-empty string passes validation. The handler rejects the unknown SKU with NotFound: existence is a business rule.

json
{
  "sku": "UNKNOWN",
  "quantity": 2
}
json
{
  "code": "NotFound",
  "issues": [],
  "message": "SKU not found"
}
Run the RPC example and inspect the handler

From a checkout of the documentation repository, run:

bash
cd .vitepress/validation/example
pnpm install --frozen-lockfile
pnpm generate
pnpm typecheck
pnpm test

The test starts a real Connectum server and sends requests over HTTP. It checks that invalid SKU and quantity values never reach the handler.

Default interceptors install validation. The browser uses the same contract and handler; this setup runs them behind an RPC endpoint.

typescript
import { createServer, defineService } from '@connectum/core';
import { createDefaultInterceptors } from '@connectum/interceptors';
import { InventoryService } from '../gen/shop/v1/inventory_pb.ts';
import { checkStock } from './inventory.ts';

export function createExampleServer(onHandler: () => void) {
    return createServer({
        services: [
            defineService(InventoryService, {
                checkStock(req) {
                    onHandler();
                    return checkStock(req);
                },
            }),
        ],
        interceptors: createDefaultInterceptors({ errorHandler: { logErrors: false } }),
        host: '127.0.0.1',
        port: 0,
        allowHTTP1: true,
        shutdown: { autoShutdown: false },
    });
}

Complete contract:

proto
syntax = "proto3";

package shop.v1;

import "buf/validate/validate.proto";

service InventoryService {
  rpc CheckStock(CheckStockRequest) returns (CheckStockResponse);
}

message CheckStockRequest {
  string sku = 1 [
    (buf.validate.field).string = {
      min_len: 1
    }
  ];
  int32 quantity = 2 [
    (buf.validate.field).int32 = {
      gt: 0
    }
  ];
}

message CheckStockResponse {
  int32 units = 1;
}

Example handler and inventory data:

typescript
import { Code, ConnectError } from '@connectrpc/connect';

// These are example inventory data, not a connection to a production database.
const stock = new Map([['A-1', 7]]);

export function checkStock(req: { sku: string }) {
    const units = stock.get(req.sku);
    if (units === undefined) {
        throw new ConnectError('SKU not found', Code.NotFound);
    }
    return { units };
}

Regenerate the descriptors after changing constraints. createDefaultInterceptors() includes validation by default; the validation dependencies still need to be installed. Defining the annotation alone does not install middleware on a server.

How validation is wired
Validate structure before business work Installed validation middleware checks regenerated protobuf constraints before serialization and the handler, returning structured input errors while business decisions remain in application code. VALID INVALID Install + fetch rules@connectrpc/validate@bufbuild/protovalidatebuf.yaml; buf dep update Proto constraintsField and message constraintsRegenerate descriptors after edits RequestUntrusted input Validation interceptorDefault / standalone; can disableBefore serializer and handler Schema valid? INVALID_ARGUMENTField path + violated ruleConstraint identifier Business validationHandler checks business stateStock · uniqueness · credit
Annotations require installed dependencies, regenerated descriptors and an active interceptor. Structural checks do not establish uniqueness, stock availability or a customer’s credit limit.

Go deeper ​

Find a section from the full guide

The detailed material is preserved on a separate page. Earlier section links still work here.