All files / forms/src validation.js

63.41% Statements 26/41
54.54% Branches 12/22
33.33% Functions 4/12
63.41% Lines 26/41

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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167                                              3x 3x 3x             4x   4x       4x   4x   6x 6x 6x 3x       1x             4x 4x   4x 4x 4x 3x 3x         4x 4x                 4x 4x                                                                                                                                     4x 3x   1x                                  
/**
 * Coherent.js Form Validation
 * 
 * Comprehensive validation utilities for forms
 * 
 * @module forms/validation
 */
 
import { validators, resolveValidator, wrapValidator } from './rules.js';
 
/**
 * Built-in validators (the same registry `@coherent.js/forms/validators`
 * exports). Each is a factory returning a `(value, formData) => error | null`
 * validator: `validators.minLength(8)`. See rules.js for the full convention.
 */
export { validators };
 
/**
 * Form Validator
 * Manages form validation state
 */
export class FormValidator {
  constructor(schema = {}) {
    this.schema = schema;
    this.errors = {};
    this.touched = {};
  }
 
  /**
   * Validate a single field
   */
  validateField(name, value, formData = {}) {
    const fieldValidators = this.schema[name];
    
    Iif (!fieldValidators) {
      return null;
    }
 
    const validatorArray = Array.isArray(fieldValidators) ? fieldValidators : [fieldValidators];
 
    for (const entry of validatorArray) {
      // Accepts `validators.required` as well as `validators.required()`.
      const validator = resolveValidator(entry);
      const error = validator ? validator(value, formData) : null;
      if (error) {
        return error;
      }
    }
 
    return null;
  }
 
  /**
   * Validate entire form
   */
  validate(formData) {
    const errors = {};
    let isValid = true;
 
    for (const [name, value] of Object.entries(formData)) {
      const error = this.validateField(name, value, formData);
      if (error) {
        errors[name] = error;
        isValid = false;
      }
    }
 
    // Check for required fields not in formData
    for (const name of Object.keys(this.schema)) {
      Iif (!(name in formData)) {
        const error = this.validateField(name, undefined, formData);
        if (error) {
          errors[name] = error;
          isValid = false;
        }
      }
    }
 
    this.errors = errors;
    return { isValid, errors };
  }
 
  /**
   * Mark field as touched
   */
  touch(name) {
    this.touched[name] = true;
  }
 
  /**
   * Check if field is touched
   */
  isTouched(name) {
    return this.touched[name] || false;
  }
 
  /**
   * Get error for field
   */
  getError(name) {
    return this.errors[name] || null;
  }
 
  /**
   * Check if field has error
   */
  hasError(name) {
    return !!this.errors[name];
  }
 
  /**
   * Clear errors
   */
  clearErrors() {
    this.errors = {};
  }
 
  /**
   * Clear touched state
   */
  clearTouched() {
    this.touched = {};
  }
 
  /**
   * Reset validator
   */
  reset() {
    this.clearErrors();
    this.clearTouched();
  }
}
 
/**
 * Create a validator.
 *
 * - `createValidator(schema)` returns a {@link FormValidator} for a
 *   `{ field: validator | validator[] }` schema.
 * - `createValidator(fn, message?)` wraps a check function as a validator: a
 *   string result is the error, another truthy result becomes `message`, a
 *   falsy one passes.
 *
 * Both entry points (`@coherent.js/forms` and `@coherent.js/forms/validators`)
 * export this same function.
 */
export function createValidator(schemaOrFn, message) {
  if (typeof schemaOrFn === 'function') {
    return wrapValidator(schemaOrFn, message);
  }
  return new FormValidator(schemaOrFn);
}
 
/**
 * Validate form data against schema
 */
export function validate(formData, schema) {
  const validator = new FormValidator(schema);
  return validator.validate(formData);
}
 
export default {
  validators,
  FormValidator,
  createValidator,
  validate
};