All files / forms/src validation.js

1.17% Statements 1/85
0% Branches 0/70
0% Functions 0/34
1.17% Lines 1/85

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 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230                      1x                                                                                                                                                                                                                                                                                                                                                                                                                                                    
/**
 * Coherent.js Form Validation
 * 
 * Comprehensive validation utilities for forms
 * 
 * @module forms/validation
 */
 
/**
 * Built-in validators
 */
export const validators = {
  required: (message = 'This field is required') => (value) => {
    if (value === null || value === undefined || value === '') {
      return message;
    }
    return null;
  },
 
  minLength: (min, message = `Minimum length is ${min}`) => (value) => {
    if (value && value.length < min) {
      return message;
    }
    return null;
  },
 
  maxLength: (max, message = `Maximum length is ${max}`) => (value) => {
    if (value && value.length > max) {
      return message;
    }
    return null;
  },
 
  min: (min, message = `Minimum value is ${min}`) => (value) => {
    if (value !== null && value !== undefined && Number(value) < min) {
      return message;
    }
    return null;
  },
 
  max: (max, message = `Maximum value is ${max}`) => (value) => {
    if (value !== null && value !== undefined && Number(value) > max) {
      return message;
    }
    return null;
  },
 
  email: (message = 'Invalid email address') => (value) => {
    if (value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
      return message;
    }
    return null;
  },
 
  url: (message = 'Invalid URL') => (value) => {
    if (value) {
      try {
        new URL(value);
      } catch {
        return message;
      }
    }
    return null;
  },
 
  pattern: (regex, message = 'Invalid format') => (value) => {
    if (value && !regex.test(value)) {
      return message;
    }
    return null;
  },
 
  matches: (fieldName, message = 'Fields do not match') => (value, formData) => {
    if (value !== formData[fieldName]) {
      return message;
    }
    return null;
  },
 
  oneOf: (options, message = 'Invalid option') => (value) => {
    if (value && !options.includes(value)) {
      return message;
    }
    return null;
  },
 
  custom: (fn, message = 'Validation failed') => (value, formData) => {
    if (!fn(value, formData)) {
      return message;
    }
    return null;
  }
};
 
/**
 * 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];
    
    if (!fieldValidators) {
      return null;
    }
 
    const validatorArray = Array.isArray(fieldValidators) ? fieldValidators : [fieldValidators];
 
    for (const validator of validatorArray) {
      const error = validator(value, formData);
      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)) {
      if (!(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 form validator
 */
export function createValidator(schema) {
  return new FormValidator(schema);
}
 
/**
 * 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
};