All files / lib validators.ts

70% Statements 14/20
80% Branches 8/10
50% Functions 2/4
70% Lines 14/20
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  1x 1x 1x   3x 2x 1x     1x     1x     5x 4x 1x     3x     1x                           1x        
import * as chalk from 'chalk';
 
import { Validator, Validators } from '../definitions';
import { isValidEmail } from './utils';
 
export const validators: Validators = {
  required: function(input: string, key?: string): boolean | string {
    if (!input) {
      if (key) {
        return `${chalk.bold(key)} must not be empty.`;
      } else {
        return 'Must not be empty.';
      }
    }
 
    return true;
  },
  email: function(input: string, key?: string): boolean | string {
    if (!isValidEmail(input)) {
      if (key) {
        return `${chalk.bold(key)} is an invalid email address.`;
      } else {
        return 'Invalid email address.';
      }
    }
 
    return true;
  }
};

export function combine(validators: Validator[]): Validator {
  return function(input: string): boolean | string {
    for (let v of validators) {
      let o = v(input);
      if (o !== true) {
        return o;
      }
    }
 
    return true;
  };
}