All files / src/validation validateField.ts

87.5% Statements 7/8
85.71% Branches 6/7
100% Functions 2/2
87.5% Lines 7/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38                                42x     42x 4x   4x       4x           4x     42x    
import type {
  CustomValidatorMap,
  FieldValue,
  FormValues,
  NormalizedField,
  NormalizedFormSchema
} from "../schema/types";
import { runBuiltInValidators } from "./validators";
 
export function validateField(
  field: NormalizedField,
  value: FieldValue,
  values: FormValues,
  schema: NormalizedFormSchema,
  validators: CustomValidatorMap = {}
): string[] {
  const builtInErrors = runBuiltInValidators(field, value);
  // Custom validators are synchronous and named explicitly to keep schema data non-executable.
  const customErrors =
    field.validators?.flatMap((validatorName) => {
      const validator = validators[validatorName];
 
      Iif (!validator) {
        return [`Validator "${validatorName}" is not registered.`];
      }
 
      const result = validator(value, {
        fieldName: field.name,
        values,
        schema
      });
 
      return result ? [result] : [];
    }) ?? [];
 
  return [...builtInErrors, ...customErrors];
}