All files / src/validation textValidation.ts

100% Statements 59/59
100% Branches 25/25
100% Functions 4/4
100% Lines 59/59

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 601x 1x 1x 1x 1x 4x 4x 1x 1x 3x 3x 3x 3x 3x 3x 1x 1x 1x 4x 4x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 27x 24x 24x 9x 9x 15x 15x 15x 15x 15x 15x 1x 1x 1x 26x 18x 18x 18x 177x 3x 3x 3x 3x 3x 177x 15x 15x 15x  
import { validationMessage } from '@/constants/validationMessages';
import type { ValidationResult } from '@/contracts/validationResult';
 
export const minLength =
  (minLength: number) =>
  (value: string): ValidationResult => {
    if ((value?.length ?? 0) >= minLength) {
      return { isValid: true };
    }
 
    return {
      isValid: false,
      errorMessage: validationMessage.minLength(minLength),
    };
  };
 
export const maxLength =
  (maxLength: number) =>
  (value: string): ValidationResult => {
    if ((value?.length ?? 0) <= maxLength) {
      return { isValid: true };
    }
 
    return {
      isValid: false,
      errorMessage: validationMessage.maxLength(maxLength),
    };
  };
 
export const lengthIsEqualTo =
  (...lengths: Array<number>) =>
  (value: string): ValidationResult => {
    const valueLength = value?.length ?? 0;
    if (lengths.includes(valueLength)) {
      return { isValid: true };
    }
 
    return {
      isValid: false,
      errorMessage: validationMessage.unexpectedValue('Length', valueLength, lengths),
    };
  };
 
export const onlyAllowedChars =
  (allowedChars: string, propName?: string) =>
  (value: string): ValidationResult => {
    const safeValue = value ?? '';
    const charArr = allowedChars.split('');
    for (const char of safeValue) {
      if (charArr.includes(char) === false) {
        return {
          isValid: false,
          errorMessage: validationMessage.unexpectedValue(propName ?? 'Character', char, charArr),
        };
      }
    }
 
    return { isValid: true };
  };