54 lines
1.4 KiB
TypeScript
54 lines
1.4 KiB
TypeScript
/**
|
|
* Shared validation utilities
|
|
*/
|
|
|
|
export class ValidationError extends Error {
|
|
constructor(message: string, public field?: string) {
|
|
super(message);
|
|
this.name = 'ValidationError';
|
|
}
|
|
}
|
|
|
|
export function validatePostBody(body: string): void {
|
|
const trimmed = body.trim();
|
|
|
|
if (trimmed.length === 0) {
|
|
throw new ValidationError('Post cannot be empty.', 'body');
|
|
}
|
|
|
|
if (body.length > 500) {
|
|
throw new ValidationError('Post is too long (max 500 characters).', 'body');
|
|
}
|
|
}
|
|
|
|
export function validateCommentBody(body: string): void {
|
|
const trimmed = body.trim();
|
|
|
|
if (trimmed.length === 0) {
|
|
throw new ValidationError('Comment cannot be empty.', 'body');
|
|
}
|
|
|
|
if (body.length > 300) {
|
|
throw new ValidationError('Comment is too long (max 300 characters).', 'body');
|
|
}
|
|
}
|
|
|
|
export function validateReportReason(reason: string): void {
|
|
const trimmed = reason.trim();
|
|
|
|
if (trimmed.length < 10) {
|
|
throw new ValidationError('Report reason must be at least 10 characters.', 'reason');
|
|
}
|
|
|
|
if (reason.length > 500) {
|
|
throw new ValidationError('Report reason is too long (max 500 characters).', 'reason');
|
|
}
|
|
}
|
|
|
|
export function validateUUID(value: string, fieldName: string): void {
|
|
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
if (!uuidRegex.test(value)) {
|
|
throw new ValidationError(`Invalid ${fieldName}.`, fieldName);
|
|
}
|
|
}
|