41 lines
1.7 KiB
TypeScript
41 lines
1.7 KiB
TypeScript
/**
|
|
* Validation ฝั่ง client ของ dynamic form สร้างเอกสาร (FR-10) — pure function ให้ unit test ได้
|
|
* เงื่อนไขตรงกับ backend (DocumentsController.Generate): required ห้ามว่าง,
|
|
* number ต้อง parse เป็นเลขได้, date ต้องเป็นวันที่ ISO ที่ parse ได้ — client เช็คก่อนเพื่อ feedback ทันที
|
|
*/
|
|
|
|
export interface FieldDefLike {
|
|
key: string
|
|
label: string
|
|
type: string
|
|
isRequired: boolean
|
|
}
|
|
|
|
export interface FieldIssue {
|
|
key: string
|
|
message: string
|
|
}
|
|
|
|
/** ตัวเลข: จำนวนเต็ม/ทศนิยม ติดลบได้ มี comma คั่นหลักได้ (ตรง NumberStyles.Number ของ backend) */
|
|
const NUMBER_RE = /^[+-]?\d+(?:\.\d+)?$/
|
|
|
|
export function validateFieldValues(
|
|
defs: FieldDefLike[],
|
|
values: Record<string, string>,
|
|
): FieldIssue[] {
|
|
const issues: FieldIssue[] = []
|
|
for (const def of defs) {
|
|
const raw = (values[def.key] ?? '').trim()
|
|
if (raw === '') {
|
|
if (def.isRequired) issues.push({ key: def.key, message: `“${def.label}” เป็นช่องที่ต้องกรอก` })
|
|
continue
|
|
}
|
|
if (def.type === 'number' && !NUMBER_RE.test(raw.replace(/,/g, ''))) {
|
|
issues.push({ key: def.key, message: `“${def.label}” ต้องเป็นตัวเลข` })
|
|
}
|
|
if (def.type === 'date' && Number.isNaN(Date.parse(raw))) {
|
|
issues.push({ key: def.key, message: `“${def.label}” ต้องเป็นวันที่ (YYYY-MM-DD)` })
|
|
}
|
|
}
|
|
return issues
|
|
}
|