All files / js/widgets DateInputWidget.tsx

95.83% Statements 23/24
95.24% Branches 20/21
83.33% Functions 5/6
95.83% Lines 23/24

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 701x   1x 1x   7x     5x 5x             1x     3x 1x     2x 2x               1x     1x   1x     3x     4x 4x 4x 1x 1x 1x 1x   3x                                    
import React from "react";
import { WidgetProps } from "./types";
import { trans } from "../i18n";
import InputWidgetBase from "./InputWidgetBase";
 
function isValidDate(year: number, month: number, day: number) {
  const date = new Date(year, month - 1, day);
  if (
    date.getFullYear() === year &&
    date.getMonth() === month - 1 &&
    date.getDate() === day
  ) {
    return true;
  }
  return false;
}
 
function validateDate(value: string) {
  if (!value) {
    return null;
  }
 
  const match = value.match(/^\s*(\d{4})-(\d{1,2})-(\d{1,2})\s*$/);
  if (
    match &&
    isValidDate(
      parseInt(match[1], 10),
      parseInt(match[2], 10),
      parseInt(match[3], 10)
    )
  ) {
    return null;
  }
 
  return trans("ERROR_INVALID_DATE");
}
 
function postprocessDate(value: string) {
  value = value.trim();
  const match = value.match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})\s*$/);
  let day, month, year;
  if (match) {
    day = parseInt(match[1], 10);
    month = parseInt(match[2], 10);
    year = parseInt(match[3], 10);
    return (
      year +
      "-" +
      (month < 10 ? "0" : "") +
      month +
      "-" +
      (day < 10 ? "0" : "") +
      day
    );
  }
  return value;
}
 
export function DateInputWidget(props: WidgetProps) {
  return (
    <InputWidgetBase
      inputType="date"
      inputAddon={<i className="fa fa-calendar" />}
      postprocessValue={postprocessDate}
      validate={validateDate}
      {...props}
    />
  );
}