54 lines
1.6 KiB
TypeScript
54 lines
1.6 KiB
TypeScript
export const sanitizeInput = (val: string, allowDecimal = false) => {
|
|
if (val === "") return ""; // 빈 값 허용
|
|
|
|
// 소숫점 허용
|
|
if (allowDecimal) {
|
|
// 숫자와 점만 허용
|
|
let cleaned = val.replace(/[^0-9.]/g, "");
|
|
// 소숫점 여러 개일 경우 첫 번째만 유지
|
|
const parts = cleaned.split(".");
|
|
if (parts.length > 2) {
|
|
cleaned = parts[0] + "." + parts.slice(1).join("");
|
|
}
|
|
return cleaned;
|
|
}
|
|
|
|
// 정수만 허용
|
|
return val.replace(/[^0-9]/g, "");
|
|
};
|
|
|
|
|
|
|
|
// utils: format Date <-> "YYYY-MM-DD" without moment
|
|
export const formatDateToYMD=(value: Date): string => {
|
|
if (!value) return "";
|
|
// value can be Date | string ("YYYY-MM-DD")
|
|
if (typeof value === "string") {
|
|
// assume already in yyyy-mm-dd
|
|
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return value;
|
|
const d = new Date(value);
|
|
if (isNaN(d.getTime())) return "";
|
|
return toYMD(d);
|
|
}
|
|
if (value instanceof Date) {
|
|
if (isNaN(value.getTime())) return "";
|
|
return toYMD(value);
|
|
}
|
|
return "";
|
|
}
|
|
|
|
const toYMD=(date: Date): string => {
|
|
// avoid timezone shift by normalizing to local date parts
|
|
const y = date.getFullYear();
|
|
const m = String(date.getMonth() + 1).padStart(2, "0");
|
|
const day = String(date.getDate()).padStart(2, "0");
|
|
return `${y}-${m}-${day}`;
|
|
}
|
|
|
|
// const parseYMDToDate=(ymd: string): Date | null => {
|
|
// if (!/^\d{4}-\d{2}-\d{2}$/.test(ymd)) return null;
|
|
// const [y, m, d] = ymd.split("-").map(Number);
|
|
// const date = new Date(y, (m - 1), d);
|
|
// // validate round-trip
|
|
// return (date.getFullYear() === y && date.getMonth() === m - 1 && date.getDate() === d) ? date : null;
|
|
// }
|