gluestick/src/schemas.ts

108 lines
2.5 KiB
TypeScript
Raw Normal View History

2023-04-26 21:21:28 -04:00
import * as Yup from "yup";
const REQUIRED = "Required.";
const USERNAME = Yup.string()
.required(REQUIRED)
.min(1, "Username is too short.");
2023-04-26 22:59:17 -04:00
const DISPLAY_NAME = Yup.string()
.required(REQUIRED)
.min(1, "Display name is too short.");
const EMAIL = Yup.string().required(REQUIRED).email("Not an email.");
2023-04-26 21:21:28 -04:00
const PASSWORD = Yup.string()
.required(REQUIRED)
.min(12, "Password must be at least 12 characters long.");
2023-04-26 22:59:17 -04:00
const CONFIRM_PASSWORD = (name: string) =>
Yup.string()
.required(REQUIRED)
.oneOf([Yup.ref(name, {})], "Passwords must match.");
const AVATAR = Yup.string().test(
"file-size",
2023-04-28 12:08:36 -04:00
"File is bigger than 2 MB.",
2023-04-26 22:59:17 -04:00
(value) => {
if (value == null) return true;
try {
const buf = Buffer.from(value, "base64");
2023-04-28 12:08:36 -04:00
return buf.length <= 2_000_000;
2023-04-26 22:59:17 -04:00
} catch (e) {
return false;
}
}
);
2023-04-26 21:21:28 -04:00
export const loginSchema = Yup.object().shape({
username: USERNAME,
password: PASSWORD
});
export type LoginFormValues = {
username: string;
password: string;
};
export const registerSchema: Yup.Schema<RegisterFormValues> =
Yup.object().shape({
username: USERNAME,
2023-04-26 22:59:17 -04:00
displayName: DISPLAY_NAME,
email: EMAIL,
2023-04-26 21:21:28 -04:00
password: PASSWORD,
2023-04-26 22:59:17 -04:00
confirmPassword: CONFIRM_PASSWORD("password"),
avatar: AVATAR
2023-04-26 21:21:28 -04:00
});
export interface RegisterFormValues {
username: string;
displayName: string;
email: string;
password: string;
confirmPassword: string;
2023-04-26 22:59:17 -04:00
avatar?: string;
}
export const aboutMeSchema: Yup.Schema<AboutMeFormValues> = Yup.object().shape({
username: USERNAME,
displayName: DISPLAY_NAME,
email: EMAIL,
avatar: AVATAR
});
export interface AboutMeFormValues {
username: string;
displayName: string;
email: string;
avatar?: string;
}
export const passwordUpdateSchema: Yup.Schema<PasswordUpdateFormValues> =
Yup.object().shape({
password: PASSWORD,
newPassword: PASSWORD,
confirmPassword: CONFIRM_PASSWORD("newPassword")
});
export interface PasswordUpdateFormValues {
password: string;
newPassword: string;
confirmPassword: string;
2023-04-26 21:21:28 -04:00
}
2023-04-27 13:47:30 -04:00
// Types specific to the server, because sometimes we omit fields (like confirmPassword)
export const registerServerSchema: Yup.Schema<RegisterServerFormValues> =
Yup.object().shape({
username: USERNAME,
displayName: DISPLAY_NAME,
email: EMAIL,
password: PASSWORD,
avatar: AVATAR
});
export interface RegisterServerFormValues {
username: string;
displayName: string;
email: string;
password: string;
avatar?: string;
}