feat: Enhance registration process with improved validation and error handling

This commit is contained in:
beilunyang
2025-01-15 18:52:11 +08:00
parent 126a4cb948
commit 075a34239b
3 changed files with 24 additions and 14 deletions

View File

@@ -1,25 +1,28 @@
import { NextResponse } from "next/server"
import { register } from "@/lib/auth"
import { authSchema } from "@/lib/validation"
import { ZodError } from "zod"
import { authSchema, AuthSchema } from "@/lib/validation"
export const runtime = "edge"
export async function POST(request: Request) {
try {
const json = await request.json()
const body = authSchema.parse(json)
await register(body.username, body.password)
return Response.json({ success: true })
} catch (error) {
if (error instanceof ZodError) {
return Response.json(
{ error: error.errors[0].message },
const json = await request.json() as AuthSchema
try {
authSchema.parse(json)
} catch (error) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : "输入格式不正确" },
{ status: 400 }
)
}
return Response.json(
const { username, password } = json
const user = await register(username, password)
return NextResponse.json({ user })
} catch (error) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : "注册失败" },
{ status: 500 }
)

View File

@@ -39,6 +39,7 @@ export function LoginForm() {
const newErrors: FormErrors = {}
if (!username) newErrors.username = "请输入用户名"
if (!password) newErrors.password = "请输入密码"
if (username.includes('@')) newErrors.username = "用户名不能包含 @ 符号"
if (password && password.length < 8) newErrors.password = "密码长度必须大于等于8位"
setErrors(newErrors)
return Object.keys(newErrors).length === 0
@@ -48,6 +49,7 @@ export function LoginForm() {
const newErrors: FormErrors = {}
if (!username) newErrors.username = "请输入用户名"
if (!password) newErrors.password = "请输入密码"
if (username.includes('@')) newErrors.username = "用户名不能包含 @ 符号"
if (password && password.length < 8) newErrors.password = "密码长度必须大于等于8位"
if (!confirmPassword) newErrors.confirmPassword = "请确认密码"
if (password !== confirmPassword) newErrors.confirmPassword = "两次输入的密码不一致"

View File

@@ -1,8 +1,13 @@
import { z } from "zod"
export const authSchema = z.object({
username: z.string().min(1, "用户名不能为空"),
password: z.string().min(8, "密码长度必须大于等于8位"),
username: z.string()
.min(1, "用户名不能为空")
.max(20, "用户名不能超过20个字符")
.regex(/^[a-zA-Z0-9_-]+$/, "用户名只能包含字母、数字、下划线和横杠")
.refine(val => !val.includes('@'), "用户名不能是邮箱格式"),
password: z.string()
.min(8, "密码长度必须大于等于8位")
})
export type AuthSchema = z.infer<typeof authSchema>