Switching away from regex to use custom formats.

This commit is contained in:
mike12345567 2024-10-22 17:42:10 +01:00
parent bdac304551
commit bd37698055
2 changed files with 24 additions and 7 deletions

View File

@ -4,7 +4,9 @@ import { generateMetadataID } from "../db/utils"
import { Document } from "@budibase/types"
import stream from "stream"
import dayjs from "dayjs"
import customParseFormat from "dayjs/plugin/customParseFormat"
dayjs.extend(customParseFormat)
const Readable = stream.Readable
export function wait(ms: number) {
@ -14,16 +16,27 @@ export function wait(ms: number) {
export const isDev = env.isDev
export const NUMBER_REGEX = /^[+-]?([0-9]*[.])?[0-9]+$/g
const ACCEPTED_DATE_FORMATS = [
"MM/DD/YYYY",
"MM/DD/YY",
"DD/MM/YYYY",
"DD/MM/YY",
"YYYY/MM/DD",
"YYYY-MM-DD",
"YYYY-MM-DDTHH:mm",
"YYYY-MM-DDTHH:mm:ss",
"YYYY-MM-DDTHH:mm:ss[Z]",
"YYYY-MM-DDTHH:mm:ss.SSS[Z]",
]
export function isDate(str: string) {
// checks for xx/xx/xx or ISO date timestamp formats
return (
/^\d{2}\/\d{2}\/\d{2,4}$|^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2})?)?$/.test(
str
) &&
dayjs(str).isValid() &&
!str.includes(",")
)
for (const format of ACCEPTED_DATE_FORMATS) {
if (dayjs(str, format, true).isValid()) {
return true
}
}
return false
}
export function removeFromArray(array: any[], element: any) {

View File

@ -21,6 +21,10 @@ describe("isDate", () => {
expect(isDate("2001-01-01T12:30:45")).toEqual(true)
})
it("should handle complete ISO format", () => {
expect(isDate("2001-01-01T12:30:00.000Z")).toEqual(true)
})
it("should return false for invalid formats", () => {
expect(isDate("")).toEqual(false)
expect(isDate("1/10")).toEqual(false)