All files / react-app/src/components/RHF/utils validator.ts

93.16% Statements 109/117
86.11% Branches 93/108
100% Functions 22/22
94.94% Lines 94/99

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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256                      73x   19x       19x 4x     15x     6x 6x   6x 3x 3x 3x   3x 3x     3x           3x 3x     3x 3x       6x 4x     11x 3x 3x   3x   3x   3x 2x     9x 2x   2x 1x                                                                                                                             8x     73x 3x       73x 6x 6x 4x 2x     2x     6x 2x     73x 14x       14x 14x       73x 15x 15x 4x 4x     4x     15x 3x 2x 2x     1x       15x         15x 1x   15x 3x     15x 1x     15x 3x 2x 1x   1x       15x 6x 4x 2x   2x       15x 2x 2x 3x   2x 1x     2x 4x   2x       15x 1x 1x       15x     73x 15x 19x 6x 6x   14x 14x      
/**
 * The validator is intended to be a replica of RHF validation.
 * To be used in backend api handlers to validate incoming/outgoing form data against document when...
 * - creating/saving form data
 * - retrieving form data
 */
import { DependencyRule, FormGroup, FormSchema, RHFOption, RHFSlotProps } from "shared-types/forms";
import { RegisterOptions } from "react-hook-form";
 
import { isNullOrUndefined, isUndefined, isRegex, getValueAndMessage, isString, ERROR } from "./is";
 
export const validateInput = (inputValue: any, rules?: RegisterOptions) => {
  const isEmpty =
    isUndefined(inputValue) ||
    inputValue === "" ||
    (Array.isArray(inputValue) && !inputValue.length);
 
  if (isEmpty && rules?.required) {
    return isString(rules.required) ? rules.required : "*Required";
  }
 
  if (!isEmpty && (!isNullOrUndefined(rules?.min) || !isNullOrUndefined(rules?.max))) {
    let exceedMax;
    let exceedMin;
    const maxOutput = getValueAndMessage(rules?.max);
    const minOutput = getValueAndMessage(rules?.min);
 
    if (!isNullOrUndefined(inputValue) && !isNaN(inputValue as number)) {
      const valueNumber = inputValue ? +inputValue : inputValue;
      Eif (!isNullOrUndefined(maxOutput.value)) {
        exceedMax = valueNumber > maxOutput.value;
      }
      Eif (!isNullOrUndefined(minOutput.value)) {
        exceedMin = valueNumber < minOutput.value;
      }
    } else {
      const valueDate = new Date(inputValue as string);
      // const convertTimeToDate = (time: unknown) =>
      //   new Date(new Date().toDateString() + " " + time);
      // // const isTime = ref.type == "time";
      // // const isWeek = ref.type == "week";
 
      Eif (isString(maxOutput.value) && inputValue) {
        exceedMax = valueDate > new Date(maxOutput.value);
      }
 
      Eif (isString(minOutput.value) && inputValue) {
        exceedMin = valueDate < new Date(minOutput.value);
      }
    }
 
    if (exceedMax) return maxOutput.message;
    if (exceedMin) return minOutput.message;
  }
 
  if ((rules?.maxLength || rules?.minLength) && !isEmpty && isString(inputValue)) {
    const maxLengthOutput = getValueAndMessage(rules?.maxLength);
    const minLengthOutput = getValueAndMessage(rules?.minLength);
    const exceedMax =
      !isNullOrUndefined(maxLengthOutput.value) && inputValue.length > +maxLengthOutput.value;
    const exceedMin =
      !isNullOrUndefined(minLengthOutput.value) && inputValue.length < +minLengthOutput.value;
 
    if (exceedMax) return maxLengthOutput.message;
    if (exceedMin) return minLengthOutput.message;
  }
 
  if (rules?.pattern && !isEmpty && isString(inputValue)) {
    const { value: patternValue, message } = getValueAndMessage(rules?.pattern);
 
    if (isRegex(patternValue) && !inputValue.match(patternValue)) {
      return message;
    }
  }
  // TODO: Add validate condition
  // if (rules?.validate) {
  //   if (isFunction(rules?.validate)) {
  //     const result = await rules?.validate(inputValue, formValues);
  //     const validateError = getValidateError(result, inputRef);
 
  //     if (validateError) {
  //       error[name] = {
  //         ...validateError,
  //         ...appendErrorsCurry(
  //           INPUT_VALIDATION_RULES.validate,
  //           validateError.message
  //         ),
  //       };
  //       if (!validateAllFieldCriteria) {
  //         setCustomValidity(validateError.message);
  //         return error;
  //       }
  //     }
  //   } else if (isObject(validate)) {
  //     let validationResult = {} as FieldError;
 
  //     for (const key in validate) {
  //       if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
  //         break;
  //       }
 
  //       const validateError = getValidateError(
  //         await validate[key](inputValue, formValues),
  //         inputRef,
  //         key
  //       );
 
  //       if (validateError) {
  //         validationResult = {
  //           ...validateError,
  //           ...appendErrorsCurry(key, validateError.message),
  //         };
 
  //         setCustomValidity(validateError.message);
 
  //         if (validateAllFieldCriteria) {
  //           error[name] = validationResult;
  //         }
  //       }
  //     }
 
  //     if (!isEmptyObject(validationResult)) {
  //       error[name] = {
  //         ref: inputRef,
  //         ...validationResult,
  //       };
  //       if (!validateAllFieldCriteria) {
  //         return error;
  //       }
  //     }
  //   }
  // }
 
  // If all checks pass, the input value is valid
  return "";
};
 
export const validateOption = (optionValue: string, options: any[]) => {
  return options.find((OPT: any) => OPT.value === optionValue);
};
 
// return true: run validation - false: skip validation
export const dependencyCheck = (dep: DependencyRule, data: any) => {
  const conditionMatched = dep.conditions.every((DC) => {
    if (DC.type === "valueNotExist") return !data[DC.name];
    if (DC.type === "expectedValue") {
      return data[DC.name] === DC.expectedValue;
    }
 
    return !!data[DC.name];
  });
 
  if (dep.effect.type === "show") return conditionMatched;
  Eif (dep.effect.type === "hide") return !conditionMatched;
};
 
export const formGroupValidator = (data: any) => (ACC: ERROR, FORM: FormGroup) => {
  Iif (FORM.dependency) {
    const depMatch = dependencyCheck(FORM.dependency, data);
    if (!depMatch) return ACC;
  }
  FORM.slots.reduce(slotValidator(data), ACC);
  return ACC;
};
 
export const slotValidator =
  (data: any) =>
  (ACC: ERROR, SLOT: RHFSlotProps): ERROR => {
    const optionValidator = (OPT: RHFOption) => {
      Iif (OPT.form) OPT.form.reduce(formGroupValidator(data), ACC);
      Iif (OPT.slots) {
        OPT.slots.reduce(slotValidator(data), ACC);
      }
      return ACC;
    };
 
    const fieldValidator = (FLD: any) => (SLOT1: RHFSlotProps) => {
      if (SLOT1.rhf === "FieldArray") {
        FLD[SLOT1.name].forEach((DAT: any) => {
          SLOT1.fields?.forEach(fieldValidator(DAT));
        });
      } else {
        slotValidator(FLD)(ACC, SLOT1);
      }
    };
 
    Iif (SLOT.dependency) {
      const depMatch = dependencyCheck(SLOT.dependency, data);
      if (!depMatch) return ACC;
    }
 
    if (SLOT.rhf === "Input") {
      ACC[SLOT.name] = validateInput(data[SLOT.name], SLOT.rules);
    }
    if (SLOT.rhf === "Textarea") {
      ACC[SLOT.name] = validateInput(data[SLOT.name], SLOT.rules);
    }
 
    if (SLOT.rhf === "Switch") {
      ACC[SLOT.name] = validateInput(data[SLOT.name], SLOT.rules);
    }
 
    if (SLOT.rhf === "Radio") {
      const validOption = SLOT.props?.options.find((OPT) => OPT.value === data[SLOT.name]);
      if (!validOption) {
        ACC[SLOT.name] = `invalid option - '${data[SLOT.name]}'`;
      } else {
        optionValidator(validOption);
      }
    }
 
    if (SLOT.rhf === "Select") {
      const validOption = SLOT.props?.options.find((OPT) => OPT.value === data[SLOT.name]);
      if (!validOption) {
        ACC[SLOT.name] = `invalid option - '${data[SLOT.name]}'`;
      } else {
        optionValidator(validOption);
      }
    }
 
    if (SLOT.rhf === "Checkbox") {
      Eif (data[SLOT.name]?.length) {
        const validList = data[SLOT.name].every((VAL: any) =>
          SLOT.props?.options.some((OPT) => OPT.value === VAL),
        );
        if (!validList) {
          ACC[SLOT.name] = `invalid option - '${data[SLOT.name]}'`;
        }
 
        const selectedOptions = SLOT.props?.options.filter((OPT) =>
          data[SLOT.name].includes(OPT.value),
        );
        selectedOptions?.forEach(optionValidator);
      }
    }
 
    if (SLOT.rhf === "FieldArray") {
      data[SLOT.name].forEach((DAT: any) => {
        SLOT.fields?.forEach(fieldValidator(DAT));
      });
    }
 
    return ACC;
  };
 
export const documentValidator = (document: FormSchema) => (data: any) => {
  return document.sections.reduce((ACC, SEC) => {
    if (SEC.dependency) {
      const depMatch = dependencyCheck(SEC.dependency, data);
      if (!depMatch) return ACC;
    }
    SEC.form.reduce(formGroupValidator(data), ACC);
    return ACC;
  }, {} as ERROR);
};