Uecko_ERP/apps/server/archive/contexts/auth/domain/value-objects/username.ts
2025-05-09 12:45:32 +02:00

42 lines
1.0 KiB
TypeScript

import { ValueObject } from "@/core/common/domain";
import { Result } from "@repo/rdx-utils";
import { z } from "zod";
interface UsernameProps {
value: string;
}
export class Username extends ValueObject<UsernameProps> {
static create(username: string): Result<Username, Error> {
const result = Username.validate(username);
return result.success
? Result.ok(new Username({ value: result.data }))
: Result.fail(new Error(result.error.errors[0].message));
}
private static validate(username: string) {
const schema = z
.string()
.min(3, { message: "Username must be at least 3 characters long" })
.max(30, { message: "Username cannot exceed 30 characters" })
.regex(/^[a-zA-Z0-9_]+$/, {
message: "Username can only contain letters, numbers, and underscores",
});
return schema.safeParse(username);
}
getValue() {
return this.props.value;
}
toString() {
return this.props.value;
}
toPrimitive() {
return this.props.value;
}
}