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

64 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-08-13 17:05:46 +01:00
import { z } from 'zod';
/**
* Regular expression to validate a data URL.
* The pattern matches data URLs that start with `data:`, optionally followed by a media type,
* optionally followed by an encoding (e.g., `base64`), and ending with base64 encoded data.
*/
export const zodDataUrlRegex = /^data:(?:[\w+\/-]+)?(?:[\w+\/-]+)?;base64,[\s\S]*$/;
/**
* 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);
* }
*/
export const zodDataUrlSchema = z.string().refine(value => zodDataUrlRegex.test(value), {
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 => {
// Regular expression for Base64 validation
const isBase64 = /^[A-Za-z0-9+/=]*$/.test(value) && (value.length % 4 === 0);
// Check if the first 20 characters do not contain a comma
return isBase64 && !value.substring(0, 20).includes(',');
}, {
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
* ```
*/