All files / src/validators min-length.ts

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

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                                          10x   3x 10x 3x   7x    
import { Validator } from "../types";
 
/**
 * Given a string, array or any other object having a `length: number`
 * property, checks the actual length against expected minimum.
 *
 * @example
 *
 * ```ts
 * import { minLength } from 'compose-validators';
 *
 * const validate = minLength(3);
 *
 * validate([1,2]) // => { minLength: 3 }
 * validate([1,2,3]) // => {}
 * validate("ab") // => { minLength: 3 }
 * validate("abc") // => {}
 * ```
 *
 * @param length minimum length allowed
 */
export const minLength = <T extends { length: number }>(
  length: number
): Validator<T> => (value: T) => {
  if (value.length < length) {
    return { minLength: length };
  }
  return {};
};