All files / src/validators required.ts

100% Statements 8/8
100% Branches 5/5
100% Functions 2/2
100% Lines 7/7

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            10x 23x     4x     19x                                                 10x 23x 6x    
import { Validator } from "../types";
 
/**
 * @internal
 * @param value
 */
const isValid = (value: any) => {
  switch (typeof value) {
    case "boolean":
    case "number":
      return true;
 
    default: {
      return Boolean(value);
    }
  }
};
 
/**
 * Checks that the value is defined and is not an empty string.
 *
 * @example
 *
 * ```ts
 * import { required } from 'compose-validators';
 *
 * required('') // => { required: true }
 * required(undefined) // => { required: true }
 * required(null) // => { required: true }
 * required('abc') // => {}
 * required(0) // => {}
 * required(false) // => {}
 * required({}) // => {}
 * required([]) // => {}
 * ```
 *
 * @param value
 */
export const required: Validator<any> = (value) => {
  if (isValid(value)) return {};
  return { required: true };
};