Validasi Kustom
Buat aturan validasi canggih untuk upload Anda.
Aturan Kustom Dasar
import { useDropup } from '@samithahansaka/dropup';
function CustomValidationUploader() {
const { files, getDropProps, getInputProps } = useDropup({
customRules: [
// Aturan 1: Periksa nama file
(file) => {
if (file.name.includes(' ')) {
return 'Nama file tidak boleh mengandung spasi';
}
return true;
},
// Aturan 2: Periksa ekstensi
(file) => {
const ext = file.name.split('.').pop()?.toLowerCase();
const blocked = ['exe', 'bat', 'cmd', 'sh'];
if (ext && blocked.includes(ext)) {
return 'File executable tidak diperbolehkan';
}
return true;
},
],
onValidationError: (errors) => {
errors.forEach(({ file, errors }) => {
alert(`${file.name}:\n${errors.join('\n')}`);
});
},
});
return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Lepas file di sini (tanpa spasi di nama, tanpa executable)</p>
</div>
);
}
Validasi Async
import { useDropup } from '@samithahansaka/dropup';
function AsyncValidationUploader() {
const { files, getDropProps, getInputProps } = useDropup({
customRules: [
// Periksa duplikat di 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 'File ini sudah pernah diupload';
}
return true;
},
// Validasi konten file
async (file) => {
if (file.type === 'application/json') {
const text = await file.text();
try {
JSON.parse(text);
return true;
} catch {
return 'File JSON tidak valid';
}
}
return true;
},
],
});
return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Lepas file di sini (divalidasi terhadap server)</p>
</div>
);
}
// Fungsi helper untuk menghitung hash file
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('');
}
Validasi Konten Gambar
import { useDropup } from '@samithahansaka/dropup';
function ImageContentValidator() {
const { files, getDropProps, getInputProps } = useDropup({
accept: 'image/*',
customRules: [
// Periksa dimensi gambar sebenarnya
async (file) => {
if (!file.type.startsWith('image/')) return true;
const dimensions = await getImageDimensions(file);
if (dimensions.width < 200 || dimensions.height < 200) {
return 'Gambar minimal harus 200x200 pixel';
}
if (dimensions.width > 4000 || dimensions.height > 4000) {
return 'Gambar tidak boleh melebihi 4000x4000 pixel';
}
return true;
},
// Periksa rasio aspek
async (file) => {
if (!file.type.startsWith('image/')) return true;
const { width, height } = await getImageDimensions(file);
const ratio = width / height;
// Wajibkan gambar yang kira-kira persegi (rasio 0.8 sampai 1.2)
if (ratio < 0.8 || ratio > 1.2) {
return 'Gambar harus kira-kira persegi (rasio aspek 0.8-1.2)';
}
return true;
},
],
});
return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Lepas gambar persegi (min 200px, maks 4000px)</p>
<div style={styles.gallery}>
{files.map(file => (
<img
key={file.id}
src={file.preview}
alt=""
style={styles.preview}
/>
))}
</div>
</div>
);
}
// Helper untuk mendapatkan dimensi gambar
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,
},
};
Validasi dengan Dependensi
import { useDropup } from '@samithahansaka/dropup';
import { useState } from 'react';
function ConditionalValidation() {
const [category, setCategory] = useState('image');
const { files, getDropProps, getInputProps } = useDropup({
// Accept dinamis berdasarkan kategori
accept: category === 'image'
? 'image/*'
: category === 'document'
? '.pdf,.doc,.docx'
: '*/*',
customRules: [
(file) => {
// Validasi spesifik kategori
if (category === 'image') {
if (!file.type.startsWith('image/')) {
return 'Silakan upload file gambar';
}
if (file.size > 5 * 1024 * 1024) {
return 'Gambar harus di bawah 5MB';
}
}
if (category === 'document') {
if (file.size > 10 * 1024 * 1024) {
return 'Dokumen harus di bawah 10MB';
}
}
return true;
},
],
});
return (
<div>
<div style={{ marginBottom: 20 }}>
<label>
<input
type="radio"
value="image"
checked={category === 'image'}
onChange={() => setCategory('image')}
/>
Gambar (maks 5MB)
</label>
<label style={{ marginLeft: 20 }}>
<input
type="radio"
value="document"
checked={category === 'document'}
onChange={() => setCategory('document')}
/>
Dokumen (maks 10MB)
</label>
</div>
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>
Lepas {category === 'image' ? 'gambar' : 'dokumen'} di sini
</p>
</div>
</div>
);
}
Pemindaian Virus/Malware
import { useDropup } from '@samithahansaka/dropup';
function MalwareScanUploader() {
const { files, state, actions, getDropProps, getInputProps } = useDropup({
customRules: [
// Pindai file dengan layanan eksternal
async (file) => {
// Upload ke layanan pemindaian virus
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 terdeteksi: ${threat}`;
}
return true;
} catch (error) {
return 'Tidak dapat memindai file. Silakan coba lagi.';
}
},
],
onValidationError: (errors) => {
errors.forEach(({ file, errors }) => {
console.error(`${file.name} ditolak:`, errors);
});
},
});
return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>File dipindai untuk malware sebelum upload</p>
</div>
);
}
Aturan Validasi Bawaan
import { useDropup, commonRules } from '@samithahansaka/dropup';
function PrebuiltRulesUploader() {
const { files, getDropProps, getInputProps } = useDropup({
customRules: [
// Aturan bawaan
commonRules.noExecutables, // Blokir .exe, .bat, dll.
commonRules.noHiddenFiles, // Blokir file yang dimulai dengan .
commonRules.maxFilenameLength(50), // Maks 50 karakter
commonRules.allowedExtensions(['.jpg', '.png', '.pdf']),
// Gabungkan dengan aturan kustom
(file) => {
if (file.name.toLowerCase().includes('temp')) {
return 'File sementara tidak diperbolehkan';
}
return true;
},
],
});
return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Validasi file ketat diaktifkan</p>
</div>
);
}
Tampilan Error Validasi
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 'Nama file terlalu panjang (maks 50 karakter)';
}
return true;
},
],
onValidationError: (errors) => {
setValidationErrors(errors);
// Bersihkan setelah 5 detik
setTimeout(() => setValidationErrors([]), 5000);
},
});
return (
<div>
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Lepas hingga 3 gambar (maks 5MB per file)</p>
</div>
{/* Error Validasi */}
{validationErrors.length > 0 && (
<div style={styles.errorContainer}>
<h4 style={styles.errorTitle}>Beberapa file ditolak:</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>
)}
{/* File yang Diterima */}
{files.length > 0 && (
<div style={styles.acceptedFiles}>
<h4>File yang diterima:</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,
},
};