All files / src/validation/address stateValidator.ts

100% Statements 9/9
100% Branches 11/11
100% Functions 2/2
100% Lines 8/8

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                            134x           1177x   1177x 561x 270x     1177x 93x     1177x    
import { VALIDATION_MESSAGES } from "@validation/messages";
import { STATE_REGEX } from "@validation/regex";
import * as Yup from "yup";
 
export interface StateValidatorConfig {
  /** Whether state is required */
  required?: boolean;
  /** Custom required error message */
  requiredMessage?: string;
  /** Custom invalid format error message */
  invalidMessage?: string;
  nullable?: boolean;
}
 
export const createStateValidator = ({
  required = false,
  nullable = false,
  requiredMessage = VALIDATION_MESSAGES.STATE_REQUIRED,
  invalidMessage = VALIDATION_MESSAGES.INVALID_STATE,
}: StateValidatorConfig = {}) => {
  let schema = nullable ? Yup.string().nullable() : Yup.string();
 
  schema = schema.test("state-format", invalidMessage, (value) => {
    if (!value) return true; // allow empty or null if not required
    return STATE_REGEX.test(value);
  });
 
  if (required) {
    schema = schema.required(requiredMessage);
  }
 
  return schema;
};