Skip to main content

Validation Overview

ReFormer provides declarative validation with built-in validators and support for custom validation.

Basic Usage​

Define validation in validation:

import { GroupNode } from '@reformer/core';
import { required, email, minLength } from '@reformer/core/validators';

const form = new GroupNode({
form: {
name: { value: '' },
email: { value: '' },
},
validation: (path) => {
required(path.name);
minLength(path.name, 2);
required(path.email);
email(path.email);
},
});

Validation State​

// Check validation state
form.valid; // true if all fields valid
form.invalid; // true if any field invalid

// Check specific field
form.controls.name.valid;
form.controls.name.errors; // { required: true } or null

Error Messages​

Access errors on individual fields:

const name = form.controls.name;

name.errors;
// null - when valid
// { required: true } - when required fails
// { minLength: { required: 2, actual: 1 } } - when minLength fails

Built-in Validators​

ValidatorDescriptionError Key
required(path.field)Field must have valuerequired
email(path.field)Valid email formatemail
minLength(path.field, n)Minimum string lengthminLength
maxLength(path.field, n)Maximum string lengthmaxLength
min(path.field, n)Minimum number valuemin
max(path.field, n)Maximum number valuemax
pattern(path.field, regex)Match regex patternpattern
url(path.field)Valid URL formaturl
phone(path.field)Valid phone formatphone
number(path.field)Must be a numbernumber
date(path.field)Valid datedate

Conditional Validation​

Apply validation only when condition is met:

import { when } from '@reformer/core/validators';

validation: (path) => {
when(
() => form.controls.contactByPhone.value === true,
(path) => {
required(path.phone);
}
);
};

Validation Timing​

Validation runs automatically when:

  • Value changes
  • Field is touched (for display purposes)
// Manual validation
form.validate(); // Validate entire form

Next Steps​