Skip to content

Repository files navigation

validators-lite

Composable cross-field validators for Angular Reactive Forms — the ones Angular doesn't ship out of the box: date ranges, conditional-required fields, and unique-in-array checks.

No hard dependency on @angular/forms — the validators are typed structurally against AbstractControl's shape (.value, .get()), so any real Angular FormGroup/FormArray satisfies them directly.

Install

npm install validators-lite

Quick start

import { FormGroup, FormControl } from '@angular/forms';
import { dateRange, conditionalRequired, uniqueInArray } from 'validators-lite';

const form = new FormGroup(
  {
    startDate: new FormControl(''),
    endDate: new FormControl(''),
    country: new FormControl(''),
    state: new FormControl(''),
  },
  {
    validators: [
      dateRange('startDate', 'endDate'),
      conditionalRequired('country', 'state', (country) => country === 'US'),
    ],
  }
);

form.errors; // { dateRange: {...} } or { conditionalRequired: true } if invalid
import { FormArray, FormControl } from '@angular/forms';
import { uniqueInArray } from 'validators-lite';

const emails = new FormArray(
  [new FormControl('a@x.com'), new FormControl('a@x.com')],
  { validators: [uniqueInArray()] }
);

emails.errors; // { uniqueInArray: { duplicateValue: 'a@x.com' } }

For a FormArray of FormGroups, pass the field name to check: uniqueInArray('email').

API

Export Signature Description
dateRange (startField, endField) => ValidatorFn Group-level; fails if startField's date is after endField's
conditionalRequired (sourceField, targetField, condition) => ValidatorFn Group-level; targetField required only when condition(sourceValue) is true
uniqueInArray (path?) => ValidatorFn Array-level; fails on duplicate values (or duplicate values at path, for arrays of objects)

All three return null when valid, and are safe to combine with other validators in a group/array's validators array.

Why no @angular/forms import?

See CASE_STUDY.md for the reasoning — short version: structural typing keeps this package small and version-agnostic across Angular releases while still being a drop-in ValidatorFn for real Reactive Forms.

License

MIT

About

Composable cross-field validators for Angular Reactve Forms - date ranges, conditional-required fields,unique-in-array checks.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages