Files
doneit-web/src/app/utils/zod.ts
T

55 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-08-13 17:05:46 +01:00
import { z } from 'zod';
/**
* Zod schema for validating data URLs.
* This schema ensures that the input string matches the format of a data URL.
*
* @example
* const result = dataUrlSchema.safeParse('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDCAAAAC0BEMAAW9R3AAAAAElFTkSuQmCC');
* if (result.success) {
* console.log('Valid data URL:', result.data);
* } else {
* console.error('Validation error:', result.error.errors);
* }
*/
2024-08-15 16:34:07 +01:00
export const zodDataUrlSchema = z.string().refine(value => value.startsWith('data:'), {
2024-08-13 17:05:46 +01:00
message: 'Invalid data URL',
});
2024-08-15 14:29:11 +01:00
//===============================================================================
2024-08-13 17:05:46 +01:00
/**
2024-08-15 14:29:11 +01:00
* A schema for validating Base64 encoded strings.
2024-08-13 17:05:46 +01:00
*
2024-08-15 14:29:11 +01:00
* This schema checks if the string is valid Base64 and ensures that the first 20 characters
* do not contain a comma.
2024-08-13 17:05:46 +01:00
*
* @example
2024-08-15 14:29:11 +01:00
* ```typescript
* const validString = 'SGVsbG8sIHdvcmxkIQ=='; // Base64 for "Hello, world!"
* const invalidString = 'SGVsbG8sIHdvcmxkIQ,,=='; // Invalid due to commas
*
* console.log(base64Schema.safeParse(validString).success); // true
* console.log(base64Schema.safeParse(invalidString).success); // false
* ```
2024-08-13 17:05:46 +01:00
*/
2024-08-15 14:29:11 +01:00
export const base64Schema = z.string().refine(value => {
2024-08-21 20:14:48 +01:00
return !value.slice(0, 20).includes(',');
2024-08-15 14:29:11 +01:00
}, {
message: 'Invalid Base64 string or comma found in the first 20 characters'
});
2024-08-13 17:05:46 +01:00
2024-08-15 14:29:11 +01:00
/**
* Validates a given string against the Base64 schema.
*
* @param input - The string to validate.
* @returns `true` if the input is valid according to the schema, `false` otherwise.
*
* @example
* ```typescript
* console.log(validateInput('SGVsbG8sIHdvcmxkIQ==')); // true
* console.log(validateInput('SGVsbG8sIHdvcmxkIQ,,==')); // false
* ```
*/