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