Перейти к основному содержимому

Пользовательская валидация

Создавайте сложные правила валидации для ваших загрузок.

Базовые пользовательские правила

import { useDropup } from '@samithahansaka/dropup';

function CustomValidationUploader() {
const { files, getDropProps, getInputProps } = useDropup({
customRules: [
// Rule 1: Check filename
(file) => {
if (file.name.includes(' ')) {
return 'Имена файлов не могут содержать пробелы';
}
return true;
},

// Rule 2: Check extension
(file) => {
const ext = file.name.split('.').pop()?.toLowerCase();
const blocked = ['exe', 'bat', 'cmd', 'sh'];
if (ext && blocked.includes(ext)) {
return 'Исполняемые файлы не разрешены';
}
return true;
},
],

onValidationError: (errors) => {
errors.forEach(({ file, errors }) => {
alert(`${file.name}:\n${errors.join('\n')}`);
});
},
});

return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Перетащите файлы сюда (без пробелов в названиях, без исполняемых файлов)</p>
</div>
);
}

Асинхронная валидация

import { useDropup } from '@samithahansaka/dropup';

function AsyncValidationUploader() {
const { files, getDropProps, getInputProps } = useDropup({
customRules: [
// Check for duplicate on server
async (file) => {
const hash = await calculateHash(file);
const response = await fetch('/api/check-duplicate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ hash, filename: file.name }),
});
const { exists } = await response.json();

if (exists) {
return 'Этот файл уже был загружен';
}
return true;
},

// Validate file content
async (file) => {
if (file.type === 'application/json') {
const text = await file.text();
try {
JSON.parse(text);
return true;
} catch {
return 'Недопустимый JSON-файл';
}
}
return true;
},
],
});

return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Перетащите файлы сюда (проверяется на сервере)</p>
</div>
);
}

// Helper function to calculate file hash
async function calculateHash(file: File): Promise<string> {
const buffer = await file.arrayBuffer();
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}

Валидация содержимого изображения

import { useDropup } from '@samithahansaka/dropup';

function ImageContentValidator() {
const { files, getDropProps, getInputProps } = useDropup({
accept: 'image/*',

customRules: [
// Check actual image dimensions
async (file) => {
if (!file.type.startsWith('image/')) return true;

const dimensions = await getImageDimensions(file);

if (dimensions.width < 200 || dimensions.height < 200) {
return 'Изображение должно быть не менее 200x200 пикселей';
}

if (dimensions.width > 4000 || dimensions.height > 4000) {
return 'Изображение не может превышать 4000x4000 пикселей';
}

return true;
},

// Check aspect ratio
async (file) => {
if (!file.type.startsWith('image/')) return true;

const { width, height } = await getImageDimensions(file);
const ratio = width / height;

// Require roughly square images (0.8 to 1.2 ratio)
if (ratio < 0.8 || ratio > 1.2) {
return 'Изображение должно быть примерно квадратным (соотношение сторон 0.8-1.2)';
}

return true;
},
],
});

return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Перетащите квадратные изображения (мин. 200 пикс., макс. 4000 пикс.)</p>

<div style={styles.gallery}>
{files.map(file => (
<img
key={file.id}
src={file.preview}
alt=""
style={styles.preview}
/>
))}
</div>
</div>
);
}

// Helper to get image dimensions
function getImageDimensions(file: File): Promise<{ width: number; height: number }> {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
resolve({ width: img.width, height: img.height });
URL.revokeObjectURL(img.src);
};
img.onerror = reject;
img.src = URL.createObjectURL(file);
});
}

const styles = {
dropzone: {
border: '2px dashed #ccc',
borderRadius: 8,
padding: 40,
textAlign: 'center' as const,
},
gallery: {
display: 'flex',
gap: 8,
marginTop: 16,
justifyContent: 'center',
},
preview: {
width: 80,
height: 80,
objectFit: 'cover' as const,
borderRadius: 4,
},
};

Валидация с зависимостями

import { useDropup } from '@samithahansaka/dropup';
import { useState } from 'react';

function ConditionalValidation() {
const [category, setCategory] = useState('image');

const { files, getDropProps, getInputProps } = useDropup({
// Dynamic accept based on category
accept: category === 'image'
? 'image/*'
: category === 'document'
? '.pdf,.doc,.docx'
: '*/*',

customRules: [
(file) => {
// Category-specific validation
if (category === 'image') {
if (!file.type.startsWith('image/')) {
return 'Пожалуйста, загрузите файл изображения';
}
if (file.size > 5 * 1024 * 1024) {
return 'Изображения должны быть меньше 5 МБ';
}
}

if (category === 'document') {
if (file.size > 10 * 1024 * 1024) {
return 'Документы должны быть меньше 10 МБ';
}
}

return true;
},
],
});

return (
<div>
<div style={{ marginBottom: 20 }}>
<label>
<input
type="radio"
value="image"
checked={category === 'image'}
onChange={() => setCategory('image')}
/>
Изображения (макс. 5 МБ)
</label>
<label style={{ marginLeft: 20 }}>
<input
type="radio"
value="document"
checked={category === 'document'}
onChange={() => setCategory('document')}
/>
Документы (макс. 10 МБ)
</label>
</div>

<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>
Перетащите {category === 'image' ? 'изображения' : 'документы'} сюда
</p>
</div>
</div>
);
}

Сканирование на вирусы/вредоносное ПО

import { useDropup } from '@samithahansaka/dropup';

function MalwareScanUploader() {
const { files, state, actions, getDropProps, getInputProps } = useDropup({
customRules: [
// Scan file with external service
async (file) => {
// Upload to virus scanning service
const formData = new FormData();
formData.append('file', file);

try {
const response = await fetch('/api/scan', {
method: 'POST',
body: formData,
});

const { safe, threat } = await response.json();

if (!safe) {
return `Обнаружено вредоносное ПО: ${threat}`;
}

return true;
} catch (error) {
return 'Не удалось проверить файл. Пожалуйста, попробуйте еще раз.';
}
},
],

onValidationError: (errors) => {
errors.forEach(({ file, errors }) => {
console.error(`${file.name} отклонен:`, errors);
});
},
});

return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Файлы проверяются на наличие вредоносного ПО перед загрузкой</p>
</div>
);
}

Встроенные правила валидации

import { useDropup, commonRules } from '@samithahansaka/dropup';

function PrebuiltRulesUploader() {
const { files, getDropProps, getInputProps } = useDropup({
customRules: [
// Built-in rules
commonRules.noExecutables, // Block .exe, .bat, etc.
commonRules.noHiddenFiles, // Block files starting with .
commonRules.maxFilenameLength(50), // Max 50 chars
commonRules.allowedExtensions(['.jpg', '.png', '.pdf']),

// Combine with custom rules
(file) => {
if (file.name.toLowerCase().includes('temp')) {
return 'Временные файлы не разрешены';
}
return true;
},
],
});

return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Включена строгая валидация файлов</p>
</div>
);
}

Отображение ошибок валидации

import { useDropup } from '@samithahansaka/dropup';
import { useState } from 'react';

type ValidationErrorType = { file: File; errors: string[] };

function ValidationErrorDisplay() {
const [validationErrors, setValidationErrors] = useState<ValidationErrorType[]>([]);

const { files, getDropProps, getInputProps } = useDropup({
accept: 'image/*',
maxSize: 5 * 1024 * 1024,
maxFiles: 3,

customRules: [
(file) => {
if (file.name.length > 50) {
return 'Имя файла слишком длинное (макс. 50 символов)';
}
return true;
},
],

onValidationError: (errors) => {
setValidationErrors(errors);

// Clear after 5 seconds
setTimeout(() => setValidationErrors([]), 5000);
},
});

return (
<div>
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Перетащите до 3 изображений (макс. 5 МБ каждое)</p>
</div>

{/* Validation Errors */}
{validationErrors.length > 0 && (
<div style={styles.errorContainer}>
<h4 style={styles.errorTitle}>Некоторые файлы были отклонены:</h4>
{validationErrors.map(({ file, errors }, index) => (
<div key={index} style={styles.errorItem}>
<strong>{file.name}</strong>
<ul style={styles.errorList}>
{errors.map((error, i) => (
<li key={i}>{error}</li>
))}
</ul>
</div>
))}
</div>
)}

{/* Accepted Files */}
{files.length > 0 && (
<div style={styles.acceptedFiles}>
<h4>Принятые файлы:</h4>
{files.map(file => (
<div key={file.id}>{file.name}</div>
))}
</div>
)}
</div>
);
}

const styles = {
dropzone: {
border: '2px dashed #ccc',
borderRadius: 8,
padding: 40,
textAlign: 'center' as const,
},
errorContainer: {
marginTop: 16,
padding: 16,
backgroundColor: '#ffebee',
borderRadius: 8,
border: '1px solid #f44336',
},
errorTitle: {
color: '#c62828',
margin: '0 0 12px',
},
errorItem: {
marginBottom: 8,
},
errorList: {
margin: '4px 0 0',
paddingLeft: 20,
color: '#c62828',
},
acceptedFiles: {
marginTop: 16,
padding: 16,
backgroundColor: '#e8f5e9',
borderRadius: 8,
},
};