All files normalHandlers.js

100% Statements 53/53
100% Branches 20/20
100% Functions 8/8
100% Lines 45/45
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            2x 2x   1x 1x       2x 2x   1x 1x       2x 2x   1x 1x       2x 2x   1x 1x       2x 2x   1x 1x       2x 2x   1x 1x       2x 2x   1x 1x         7x   7x   2x 2x 2x   2x 2x 2x   2x 2x 2x   1x 1x 1x   7x   3x 3x    
// @ts-check
 
import is from 'is_js';
import { NAME_PLACEHOLDER, throwError } from './helpers';
 
export function enumHandler(value, schema) {
  const isValid = is.inArray(value, schema.enum);
  if (isValid) return;
 
  const errorText = `Value of ${NAME_PLACEHOLDER} should be within [${schema.enum.toString()}].`;
  throwError(value, errorText);
}
 
export function matchRegexHandler(value, schema) {
  const isValid = schema.matchRegex.test(value);
  if (isValid) return;
 
  const errorText = `Value of ${NAME_PLACEHOLDER} is not valid.`;
  throwError(value, errorText);
}
 
export function isEmailHandler(value, schema) {
  const isValid = is.email(value);
  if (isValid) return;
 
  const errorText = `${NAME_PLACEHOLDER} should be email.`;
  throwError(value, errorText);
}
 
export function isUrlHandler(value, schema) {
  const isValid = is.url(value);
  if (isValid) return;
 
  const errorText = `${NAME_PLACEHOLDER} should be a URL.`;
  throwError(value, errorText);
}
 
export function isCreditCardHandler(value, schema) {
  const isValid = is.creditCard(value * 1);
  if (isValid) return;
 
  const errorText = `${NAME_PLACEHOLDER} should be a credit card number.`;
  throwError(value, errorText);
}
 
export function isHexColorHandler(value, schema) {
  const isValid = is.hexColor(value);
  if (isValid) return;
 
  const errorText = `${NAME_PLACEHOLDER} should be a hex color.`;
  throwError(value, errorText);
}
 
export function notEmptyHandler(value, schema) {
  const isValid = is.not.empty(value);
  if (isValid) return;
 
  const errorText = `${NAME_PLACEHOLDER} should not be empty.`;
  throwError(value, errorText);
}
 
export function isIPHandler(value, schema) {
  let isValid;
  let ipString = '';
 
  switch (schema.isIP) {
    case 'v4':
      isValid = is.ipv4(value);
      ipString = 'IPv4';
      break;
    case 'v6':
      isValid = is.ipv6(value);
      ipString = 'IPv6';
      break;
    case 'all':
      isValid = is.ip(value);
      ipString = 'IP';
      break;
    default:
      isValid = is.ip(value);
      ipString = 'IP';
      break;
  }
  if (isValid) return;
 
  const errorText = `${NAME_PLACEHOLDER} should be ${ipString} address.`;
  throwError(value, errorText);
}