All files / src/validators string.ts

100% Statements 17/17
100% Branches 16/16
100% Functions 5/5
100% Lines 9/9

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 44 45                    11x   9x                 4x   2x                 5x   3x       9x 9x   7x      
import { Validator } from '..';
import { isNullOrUndefined } from '../utils/is-defined';
import { Countries, isInvalidPostalCode } from '../utils/postal-codes';
 
/**
 * Passes if string only contains alphabetical characters.
 * @param value the string to validate
 * @returns why the validator failed
 */
export function isAlpha(value: string | null | undefined): string | void {
  if (isNullOrUndefined(value)) return;
 
  if (!/[A-z ]+/.test(value)) return 'includes non alpha characters';
}
 
/**
 * Passes if string only contains alphanumeric characters.
 * @param value the string to validate
 * @returns why the validator failed
 */
export function isAlphaNumeric(value: string | null | undefined): string | void {
  if (isNullOrUndefined(value)) return;
 
  if (!/[A-z \d]+/.test(value)) return 'includes non alpha-numeric characters';
}
 
/**
 * Passes if string only contains numeric characters.
 * @param value the string to validate
 * @returns why the validator failed
 */
export function isNumeric(value: string | null | undefined): string | void {
  if (isNullOrUndefined(value)) return;
 
  if (!/\d+/.test(value)) return 'includes non numeric characters';
}
 
export function isPostalCode(countryCode: Countries): Validator.Fn<string | null | undefined> {
  return (value: string | null | undefined): string | void => {
    if (isNullOrUndefined(value)) return;
 
    if (isInvalidPostalCode(countryCode, value)) return `is an invalid postal code for "${countryCode}"`;
  };
}