64 lines
1.8 KiB
TypeScript
64 lines
1.8 KiB
TypeScript
import { ApiError } from "@/lib/api";
|
|
|
|
export function validateUsername(raw: string): string {
|
|
const trimmed = raw.trim();
|
|
if (trimmed.length < 2 || trimmed.length > 16) {
|
|
throw new ApiError("用户名需要 2-16 个字符");
|
|
}
|
|
return trimmed;
|
|
}
|
|
|
|
export function validatePassword(password: string, label = "密码"): void {
|
|
if (password.length < 6) {
|
|
throw new ApiError(`${label}至少 6 个字符`);
|
|
}
|
|
if (password.length > 128) {
|
|
throw new ApiError(`${label}不能超过 128 个字符`);
|
|
}
|
|
}
|
|
|
|
export function validateEmail(email: string): void {
|
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
|
throw new ApiError("邮箱格式不正确");
|
|
}
|
|
}
|
|
|
|
export function validateIdeaContent(raw: unknown): string {
|
|
if (!raw || typeof raw !== "string" || raw.trim().length === 0) {
|
|
throw new ApiError("内容不能为空");
|
|
}
|
|
const trimmed = raw.trim();
|
|
if (trimmed.length > 200) {
|
|
throw new ApiError("内容不能超过 200 字");
|
|
}
|
|
return trimmed;
|
|
}
|
|
|
|
export function validateRoomName(raw: unknown, fallback = "我们的周末"): string {
|
|
const trimmed = ((raw as string) || "").trim() || fallback;
|
|
if (trimmed.length > 30) {
|
|
throw new ApiError("房间名不能超过 30 个字");
|
|
}
|
|
return trimmed;
|
|
}
|
|
|
|
export function requireString(value: unknown, fieldName: string): string {
|
|
if (!value || typeof value !== "string" || !value.trim()) {
|
|
throw new ApiError(`${fieldName}不能为空`);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
const PANIC_ROOM_ID_REGEX = /^[A-Z0-9]{6}$/;
|
|
|
|
export function validatePanicRoomId(raw: unknown): string {
|
|
if (!raw || typeof raw !== "string") {
|
|
throw new ApiError("roomId 不能为空");
|
|
}
|
|
const roomId = raw.trim().toUpperCase();
|
|
if (!PANIC_ROOM_ID_REGEX.test(roomId)) {
|
|
throw new ApiError("房间号格式无效,应为 6 位字母数字", 400);
|
|
}
|
|
return roomId;
|
|
}
|