Validação Personalizada
Crie regras de validação sofisticadas para seus uploads.
Regras Personalizadas Básicas
import { useDropup } from '@samithahansaka/dropup';
function CustomValidationUploader() {
const { files, getDropProps, getInputProps } = useDropup({
customRules: [
// Regra 1: Verificar nome do arquivo
(file) => {
if (file.name.includes(' ')) {
return 'Nomes de arquivo não podem conter espaços';
}
return true;
},
// Regra 2: Verificar extensão
(file) => {
const ext = file.name.split('.').pop()?.toLowerCase();
const blocked = ['exe', 'bat', 'cmd', 'sh'];
if (ext && blocked.includes(ext)) {
return 'Arquivos executáveis não são permitidos';
}
return true;
},
],
onValidationError: (errors) => {
errors.forEach(({ file, errors }) => {
alert(`${file.name}:\n${errors.join('\n')}`);
});
},
});
return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Solte arquivos aqui (sem espaços nos nomes, sem executáveis)</p>
</div>
);
}
Validação Assíncrona
import { useDropup } from '@samithahansaka/dropup';
function AsyncValidationUploader() {
const { files, getDropProps, getInputProps } = useDropup({
customRules: [
// Verificar duplicados no servidor
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 'Este arquivo já foi enviado';
}
return true;
},
// Validar conteúdo do arquivo
async (file) => {
if (file.type === 'application/json') {
const text = await file.text();
try {
JSON.parse(text);
return true;
} catch {
return 'Arquivo JSON inválido';
}
}
return true;
},
],
});
return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Solte arquivos aqui (validados no servidor)</p>
</div>
);
}
// Função auxiliar para calcular hash do arquivo
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('');
}
Validação de Conteúdo de Imagem
import { useDropup } from '@samithahansaka/dropup';
function ImageContentValidator() {
const { files, getDropProps, getInputProps } = useDropup({
accept: 'image/*',
customRules: [
// Verificar dimensões reais da imagem
async (file) => {
if (!file.type.startsWith('image/')) return true;
const dimensions = await getImageDimensions(file);
if (dimensions.width < 200 || dimensions.height < 200) {
return 'A imagem deve ter pelo menos 200x200 pixels';
}
if (dimensions.width > 4000 || dimensions.height > 4000) {
return 'A imagem não pode exceder 4000x4000 pixels';
}
return true;
},
// Verificar proporção
async (file) => {
if (!file.type.startsWith('image/')) return true;
const { width, height } = await getImageDimensions(file);
const ratio = width / height;
// Exigir imagens aproximadamente quadradas (proporção 0.8 a 1.2)
if (ratio < 0.8 || ratio > 1.2) {
return 'A imagem deve ser aproximadamente quadrada (proporção 0.8-1.2)';
}
return true;
},
],
});
return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Solte imagens quadradas (mín 200px, máx 4000px)</p>
<div style={styles.gallery}>
{files.map(file => (
<img
key={file.id}
src={file.preview}
alt=""
style={styles.preview}
/>
))}
</div>
</div>
);
}
// Auxiliar para obter dimensões da imagem
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,
},
};
Validação com Dependências
import { useDropup } from '@samithahansaka/dropup';
import { useState } from 'react';
function ConditionalValidation() {
const [category, setCategory] = useState('image');
const { files, getDropProps, getInputProps } = useDropup({
// Accept dinâmico baseado na categoria
accept: category === 'image'
? 'image/*'
: category === 'document'
? '.pdf,.doc,.docx'
: '*/*',
customRules: [
(file) => {
// Validação específica por categoria
if (category === 'image') {
if (!file.type.startsWith('image/')) {
return 'Por favor, envie um arquivo de imagem';
}
if (file.size > 5 * 1024 * 1024) {
return 'Imagens devem ter menos de 5MB';
}
}
if (category === 'document') {
if (file.size > 10 * 1024 * 1024) {
return 'Documentos devem ter menos de 10MB';
}
}
return true;
},
],
});
return (
<div>
<div style={{ marginBottom: 20 }}>
<label>
<input
type="radio"
value="image"
checked={category === 'image'}
onChange={() => setCategory('image')}
/>
Imagens (máx 5MB)
</label>
<label style={{ marginLeft: 20 }}>
<input
type="radio"
value="document"
checked={category === 'document'}
onChange={() => setCategory('document')}
/>
Documentos (máx 10MB)
</label>
</div>
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>
Solte {category === 'image' ? 'imagens' : 'documentos'} aqui
</p>
</div>
</div>
);
}
Verificação de Vírus/Malware
import { useDropup } from '@samithahansaka/dropup';
function MalwareScanUploader() {
const { files, state, actions, getDropProps, getInputProps } = useDropup({
customRules: [
// Escanear arquivo com serviço externo
async (file) => {
// Enviar para serviço de verificação de vírus
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 `Malware detectado: ${threat}`;
}
return true;
} catch (error) {
return 'Não foi possível escanear o arquivo. Tente novamente.';
}
},
],
onValidationError: (errors) => {
errors.forEach(({ file, errors }) => {
console.error(`${file.name} rejeitado:`, errors);
});
},
});
return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Arquivos são escaneados para malware antes do upload</p>
</div>
);
}
Regras de Validação Pré-construídas
import { useDropup, commonRules } from '@samithahansaka/dropup';
function PrebuiltRulesUploader() {
const { files, getDropProps, getInputProps } = useDropup({
customRules: [
// Regras integradas
commonRules.noExecutables, // Bloquear .exe, .bat, etc.
commonRules.noHiddenFiles, // Bloquear arquivos começando com .
commonRules.maxFilenameLength(50), // Máx 50 caracteres
commonRules.allowedExtensions(['.jpg', '.png', '.pdf']),
// Combinar com regras personalizadas
(file) => {
if (file.name.toLowerCase().includes('temp')) {
return 'Arquivos temporários não são permitidos';
}
return true;
},
],
});
return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Validação estrita de arquivos ativada</p>
</div>
);
}
Exibição de Erros de Validação
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 'Nome do arquivo muito longo (máx 50 caracteres)';
}
return true;
},
],
onValidationError: (errors) => {
setValidationErrors(errors);
// Limpar após 5 segundos
setTimeout(() => setValidationErrors([]), 5000);
},
});
return (
<div>
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Solte até 3 imagens (máx 5MB cada)</p>
</div>
{/* Erros de Validação */}
{validationErrors.length > 0 && (
<div style={styles.errorContainer}>
<h4 style={styles.errorTitle}>Alguns arquivos foram rejeitados:</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>
)}
{/* Arquivos Aceitos */}
{files.length > 0 && (
<div style={styles.acceptedFiles}>
<h4>Arquivos aceitos:</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,
},
};