From 2fe0a8c3f0fb64c9dff14e6e406f799101bf5c76 Mon Sep 17 00:00:00 2001 From: James Collins Date: Fri, 17 Feb 2023 12:38:15 +1000 Subject: [PATCH] added datetime validation --- resources/js/helpers/validate.ts | 78 ++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/resources/js/helpers/validate.ts b/resources/js/helpers/validate.ts index e3069d9..11d1bd9 100644 --- a/resources/js/helpers/validate.ts +++ b/resources/js/helpers/validate.ts @@ -1,5 +1,6 @@ import { parseAusDate, + parseAusDateTime, isValidTime, convertTimeToMinutes, } from "../helpers/datetime"; @@ -479,6 +480,83 @@ export function Time(options?: ValidationTimeOptions): ValidationTimeObject { }; } +/** + * DATETIME + */ +interface ValidationDateTimeOptions { + before: string; + after: string; + invalidMessage?: string | ((options: ValidationDateTimeOptions) => string); + invalidBeforeMessage?: + | string + | ((options: ValidationDateTimeOptions) => string); + invalidAfterMessage?: + | string + | ((options: ValidationDateTimeOptions) => string); +} + +interface ValidationDateTimeObject extends ValidationDateTimeOptions { + validate: (value: string) => ValidationResult; +} + +const defaultValidationDateTimeOptions: ValidationDateTimeOptions = { + before: "", + after: "", + invalidMessage: "Must be a valid date and time.", + invalidBeforeMessage: (options: ValidationDateTimeOptions) => { + return `Must be a date/time before ${options.before}.`; + }, + invalidAfterMessage: (options: ValidationDateTimeOptions) => { + return `Must be a date/time after ${options.after}.`; + }, +}; + +/** + * Validate field is in a valid Date format + * + * @param options options data + * @returns ValidationDateObject + */ +export function DateTime( + options?: ValidationDateTimeOptions +): ValidationDateTimeObject { + options = { ...defaultValidationDateTimeOptions, ...(options || {}) }; + + return { + ...options, + validate: function (value: string): ValidationResult { + let valid = true; + let invalidMessageType = "invalidMessage"; + + const parsedDate = parseAusDateTime(value); + + if (parsedDate != null) { + const beforeDate = parseAusDateTime(options?.before || ""); + const afterDate = parseAusDateTime(options?.after || ""); + if (beforeDate != null && parsedDate > beforeDate) { + valid = false; + invalidMessageType = "invalidBeforeMessage"; + } + if (afterDate != null && parsedDate > afterDate) { + valid = false; + invalidMessageType = "invalidAfterMessage"; + } + } else { + valid = false; + } + + return { + valid: valid, + invalidMessages: [ + typeof this[invalidMessageType] === "string" + ? this[invalidMessageType] + : this[invalidMessageType](this), + ], + }; + }, + }; +} + /** * CUSTOM */