Uecko_ERP/apps/server/src/contexts/auth/domain/value-objects/username.ts

38 lines
981 B
TypeScript
Raw Normal View History

2025-04-22 15:09:57 +00:00
import { ValueObject } from "core/common/domain";
import { Result } from "core/common/helpers";
2025-01-29 19:02:59 +00:00
import { z } from "zod";
2025-02-20 18:55:24 +00:00
interface UsernameProps {
value: string;
}
export class Username extends ValueObject<UsernameProps> {
2025-01-29 19:02:59 +00:00
static create(username: string): Result<Username, Error> {
const result = Username.validate(username);
return result.success
2025-02-20 18:55:24 +00:00
? Result.ok(new Username({ value: result.data }))
2025-01-29 19:02:59 +00:00
: 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);
}
2025-02-20 18:55:24 +00:00
getValue() {
return this.props.value;
}
toString() {
return this.props.value;
}
2025-01-29 19:02:59 +00:00
}