All files / src/validation/address countryValidator.ts

100% Statements 7/7
83.33% Branches 10/12
100% Functions 1/1
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                                                      1644x   1644x   1644x 318x     1644x 1644x     1644x    
import { VALIDATION_MESSAGES } from "@validation/messages";
import { COUNTRY_CODE_REGEX } from "@validation/regex";
import * as Yup from "yup";
 
/**
 * Options:
 * - required: boolean
 * - nullable: boolean
 * - regex: custom regex (default COUNTRY_CODE_REGEX)
 * - allowAnyValue: skip regex validation
 * - message: custom message
 */
export function createCountryValidator(
  options: {
    required?: boolean;
    nullable?: boolean;
    regex?: RegExp;
    allowAnyValue?: boolean;
    message?: string;
  } = {},
) {
  const {
    required = false,
    nullable = true,
    regex = COUNTRY_CODE_REGEX,
    allowAnyValue = false,
    message = VALIDATION_MESSAGES.COUNTRY_REQUIRED,
  } = options;
 
  let schema = nullable ? Yup.string().nullable() : Yup.string();
 
  if (required) {
    schema = schema.required(message);
  }
 
  Eif (!allowAnyValue) {
    schema = schema.matches(regex, message);
  }
 
  return schema;
}