All files / validation textValidation.ts

83.07% Statements 54/65
100% Branches 18/18
75% Functions 3/4
83.07% Lines 54/65

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 661x 1x 1x 1x 44x 4x 1x 1x 3x 3x 3x 1x 1x 1x 35x 5x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 4x 4x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x                        
import { ValidationResult } from '@contracts/validationResult';
 
export const minLength =
  (minLength: number) =>
  (value: string): ValidationResult => {
    if ((value?.length ?? 0) >= minLength) {
      return { isValid: true };
    }
 
    return { isValid: false, errorMessage: `Minimum length required is ${minLength}` };
  };
 
export const maxLength =
  (maxLength: number) =>
  (value: string): ValidationResult => {
    if ((value?.length ?? 0) <= maxLength) {
      return { isValid: true };
    }
 
    return {
      isValid: false,
      errorMessage: `Text is too long! Maximum length allowed is ${maxLength}`,
    };
  };
 
export const shouldBeUrl = (value: string): ValidationResult => {
  const validationFailures: Array<string> = [];
 
  const safeValue = `${value}`;
  // const shouldStartWith = ['http://', 'https://'];
  // const hasStartWith = shouldStartWith.filter((h) => safeValue.includes?.(h)).length > 0;
  // if (!hasStartWith) {
  //   validationFailures.push(
  //     `Should start with one of ${shouldStartWith.map((s) => `'${s}'`).join(' or ')}.`,
  //   );
  // }
 
  const numPeriods = safeValue.split('').filter((c) => c === '.').length;
  const isLastCharPeriod = safeValue[safeValue.length - 1] === '.';
  if (numPeriods < 1 || isLastCharPeriod) {
    validationFailures.push('Should have at least one period in a sensible location.');
  }
 
  if (validationFailures.length > 0) {
    return {
      isValid: false,
      errorMessage: `Should be a valid link/url. (${value}) does not meet the requirements: ${validationFailures.join('. ')}.`,
    };
  }
 
  return { isValid: true };
};
 
export const shouldBeYoutubeUrl = (value: string): ValidationResult => {
  const safeValue = `${value}`;
  const youtubePartialUrl = 'https://www.youtube.com/watch?v=';
  if (safeValue.includes(youtubePartialUrl)) {
    return { isValid: true };
  }

  return {
    isValid: false,
    errorMessage: `Youtube url should start with ${youtubePartialUrl}`,
  };
};