100 lines
2.3 KiB
TypeScript
100 lines
2.3 KiB
TypeScript
import { z } from 'zod';
|
|
import axios from 'axios';
|
|
|
|
interface ZodMessages {
|
|
required_error: string;
|
|
invalid_type_error: string;
|
|
invalid_string: Record<string, string>;
|
|
too_small: Record<string, string>;
|
|
too_big: Record<string, string>;
|
|
custom: Record<string, string>;
|
|
}
|
|
|
|
class ZodMessageService {
|
|
private static instance: ZodMessageService;
|
|
private messages: ZodMessages | null = null;
|
|
|
|
private constructor() {}
|
|
|
|
static getInstance(): ZodMessageService {
|
|
if (!ZodMessageService.instance) {
|
|
ZodMessageService.instance = new ZodMessageService();
|
|
}
|
|
return ZodMessageService.instance;
|
|
}
|
|
|
|
async loadMessages(): Promise<void> {
|
|
try {
|
|
const response = await axios.get<ZodMessages>('/api/language/zod-messages', {
|
|
headers: {
|
|
'Accept-Language': navigator.language || 'tr'
|
|
}
|
|
});
|
|
this.messages = response.data;
|
|
} catch (error) {
|
|
console.error('Failed to load Zod messages:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
// Helper to create Zod schemas with localized messages
|
|
string() {
|
|
if (!this.messages) throw new Error('Messages not loaded');
|
|
|
|
return z.string({
|
|
required_error: this.messages.required_error,
|
|
invalid_type_error: this.messages.invalid_type_error
|
|
});
|
|
}
|
|
|
|
email() {
|
|
return this.string().email(this.messages?.invalid_string.email);
|
|
}
|
|
|
|
password() {
|
|
return this.string()
|
|
.min(8, { message: this.messages?.too_small.string.replace('{min}', '8') })
|
|
.regex(
|
|
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/,
|
|
{ message: this.messages?.custom.strong_password }
|
|
);
|
|
}
|
|
|
|
// Add more schema helpers as needed
|
|
}
|
|
|
|
// Export singleton instance
|
|
export const zodMessages = ZodMessageService.getInstance();
|
|
|
|
// Usage example:
|
|
/*
|
|
import { z } from 'zod';
|
|
import { zodMessages } from './validation/zodMessages';
|
|
|
|
// In your component:
|
|
useEffect(() => {
|
|
zodMessages.loadMessages();
|
|
}, []);
|
|
|
|
const loginSchema = z.object({
|
|
email: zodMessages.email(),
|
|
password: zodMessages.password(),
|
|
confirmPassword: zodMessages.string()
|
|
}).refine(
|
|
(data) => data.password === data.confirmPassword,
|
|
{
|
|
message: zodMessages.messages?.custom.password_match,
|
|
path: ["confirmPassword"]
|
|
}
|
|
);
|
|
|
|
// Use with React Hook Form
|
|
const {
|
|
register,
|
|
handleSubmit,
|
|
formState: { errors }
|
|
} = useForm({
|
|
resolver: zodResolver(loginSchema)
|
|
});
|
|
*/
|