All files stringHandlers.js

100% Statements 42/42
100% Branches 16/16
100% Functions 8/8
100% Lines 34/34
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                          5x   5x   2x 2x       4x 4x   1x 1x       2x 2x   1x 1x       2x 2x   1x 1x       2x 2x   1x 1x       2x 2x 2x   1x 1x       2x 2x   1x 1x       2x 2x 2x   1x 1x    
// @ts-check
 
import is from 'is_js';
import { NAME_PLACEHOLDER, throwError } from './helpers';
 
/**
 * This function will check if the value matches the min
 * It will throw Error if not valid, and return nothing if valid.
 * @export
 * @param {object} value
 * @param {object} schema
 */
export function minLengthHandler(value, schema) {
  const isValid = is.above(value.length, schema.minLength);
 
  if (isValid) return;
 
  const errorText = `${NAME_PLACEHOLDER}'s length should be greater than ${schema.minLength}. Current: ${value.length}`;
  throwError(value, errorText);
}
 
export function maxLengthHandler(value, schema) {
  const isValid = is.under(value.length, schema.maxLength);
  if (isValid) return;
 
  const errorText = `${NAME_PLACEHOLDER}'s length should be less than ${schema.maxLength}. Current: ${value.length}`;
  throwError(value, errorText);
}
 
export function includeHandler(value, schema) {
  const isValid = is.include(value, schema.include);
  if (isValid) return;
 
  const errorText = `${NAME_PLACEHOLDER} should include ${schema.include}. Current: ${value}`;
  throwError(value, errorText);
}
 
export function excludeHandler(value, schema) {
  const isValid = is.not.include(value, schema.exclude);
  if (isValid) return;
 
  const errorText = `${NAME_PLACEHOLDER} should not include ${schema.exclude}. Current: ${value}`;
  throwError(value, errorText);
}
 
export function startWithHandler(value, schema) {
  const isValid = is.startWith(value, schema.startWith);
  if (isValid) return;
 
  const errorText = `${NAME_PLACEHOLDER} should start with '${schema.startWith}'.`;
  throwError(value, errorText);
}
 
export function notStartWithHandler(value, schema) {
  const target = schema.notStartWith;
  const isValid = is.not.startWith(value, target);
  if (isValid) return;
 
  const errorText = `${NAME_PLACEHOLDER} should not start with '${target}'.`;
  throwError(value, errorText);
}
 
export function endWithHandler(value, schema) {
  const isValid = is.endWith(value, schema.endWith);
  if (isValid) return;
 
  const errorText = `${NAME_PLACEHOLDER} should end with '${schema.endWith}'.`;
  throwError(value, errorText);
}
 
export function notEndWithHandler(value, schema) {
  const target = schema.notEndWith;
  const isValid = is.not.endWith(value, target);
  if (isValid) return;
 
  const errorText = `${NAME_PLACEHOLDER} should not end with '${target}'.`;
  throwError(value, errorText);
}