Files
web/components/Forms/Edit/Profile/schema.ts
2024-07-01 15:38:50 +02:00

99 lines
2.7 KiB
TypeScript

import { z } from "zod"
import { Key } from "@/components/TempDesignSystem/Form/NewPassword/newPassword"
import { phoneValidator } from "@/utils/phoneValidator"
const countryRequiredMsg = "Country is required"
export const editProfileSchema = z
.object({
address: z.object({
city: z.string().optional(),
countryCode: z
.string({
required_error: countryRequiredMsg,
invalid_type_error: countryRequiredMsg,
})
.min(1, countryRequiredMsg),
streetAddress: z.string().optional(),
zipCode: z.string().min(1, "Zip code is required"),
}),
dateOfBirth: z.string().min(1),
email: z.string().email(),
language: z.string(),
phoneNumber: phoneValidator(
"Phone is required",
"Please enter a valid phone number"
),
currentPassword: z.string().optional(),
newPassword: z.string().optional(),
retypeNewPassword: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.currentPassword) {
if (!data.newPassword) {
ctx.addIssue({
code: "custom",
message: "New password is required",
path: ["newPassword"],
})
}
if (!data.retypeNewPassword) {
ctx.addIssue({
code: "custom",
message: "Retype new password is required",
path: ["retypeNewPassword"],
})
}
} else {
if (data.newPassword || data.retypeNewPassword) {
ctx.addIssue({
code: "custom",
message: "Current password is required",
path: ["currentPassword"],
})
}
}
if (data.newPassword) {
const msgs = []
if (data.newPassword.length < 10 || data.newPassword.length > 40) {
msgs.push(Key.CHAR_LENGTH)
}
if (!data.newPassword.match(/[A-Z]/g)) {
msgs.push(Key.UPPERCASE)
}
if (!data.newPassword.match(/[0-9]/g)) {
msgs.push(Key.NUM)
}
if (!data.newPassword.match(/[^A-Za-z0-9]/g)) {
msgs.push(Key.SPECIAL_CHAR)
}
if (msgs.length) {
ctx.addIssue({
code: "custom",
message: msgs.join(","),
path: ["newPassword"],
})
}
}
if (data.newPassword && !data.retypeNewPassword) {
ctx.addIssue({
code: "custom",
message: "Retype new password is required",
path: ["retypeNewPassword"],
})
}
if (data.retypeNewPassword !== data.newPassword) {
ctx.addIssue({
code: "custom",
message: "Retype new password does not match new password",
path: ["retypeNewPassword"],
})
}
})
export type EditProfileSchema = z.infer<typeof editProfileSchema>