ප්‍රධාන අන්තර්ගතයට පනින්න

Custom Validation

ඔබගේ uploads සඳහා සංකීර්ණ validation rules සාදන්න.

මූලික Custom Rules

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

function CustomValidationUploader() {
const { files, getDropProps, getInputProps } = useDropup({
customRules: [
// Rule 1: ගොනු නාමය පරීක්ෂා කරන්න
(file) => {
if (file.name.includes(' ')) {
return 'ගොනු නාම වල spaces තිබීමට නොහැකිය';
}
return true;
},

// Rule 2: Extension පරීක්ෂා කරන්න
(file) => {
const ext = file.name.split('.').pop()?.toLowerCase();
const blocked = ['exe', 'bat', 'cmd', 'sh'];
if (ext && blocked.includes(ext)) {
return 'Executable ගොනු අවසර නැත';
}
return true;
},
],

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

return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>ගොනු මෙතැනට දමන්න (නම් වල spaces නැත, executables නැත)</p>
</div>
);
}

Async Validation

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

function AsyncValidationUploader() {
const { files, getDropProps, getInputProps } = useDropup({
customRules: [
// Server එකේ duplicate පරීක්ෂා කරන්න
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 'මෙම ගොනුව දැනටමත් upload වී ඇත';
}
return true;
},

// ගොනු content validate කරන්න
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>ගොනු මෙතැනට දමන්න (server සමඟ validate වේ)</p>
</div>
);
}

// File hash ගණනය කිරීමට helper function
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('');
}

Image Content Validation

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

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

customRules: [
// සැබෑ image dimensions පරීක්ෂා කරන්න
async (file) => {
if (!file.type.startsWith('image/')) return true;

const dimensions = await getImageDimensions(file);

if (dimensions.width < 200 || dimensions.height < 200) {
return 'Image අවම වශයෙන් 200x200 pixels විය යුතුය';
}

if (dimensions.width > 4000 || dimensions.height > 4000) {
return 'Image 4000x4000 pixels ඉක්මවිය නොහැකිය';
}

return true;
},

// Aspect ratio පරීක්ෂා කරන්න
async (file) => {
if (!file.type.startsWith('image/')) return true;

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

// දළ වශයෙන් square images අවශ්‍යයි (0.8 to 1.2 ratio)
if (ratio < 0.8 || ratio > 1.2) {
return 'Image දළ වශයෙන් square විය යුතුය (aspect ratio 0.8-1.2)';
}

return true;
},
],
});

return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Square images දමන්න (අවම 200px, උපරිම 4000px)</p>

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

// Image dimensions ලබා ගැනීමට Helper
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,
},
};

Dependencies සමඟ Validation

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

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

const { files, getDropProps, getInputProps } = useDropup({
// Category අනුව Dynamic accept
accept: category === 'image'
? 'image/*'
: category === 'document'
? '.pdf,.doc,.docx'
: '*/*',

customRules: [
(file) => {
// Category-specific validation
if (category === 'image') {
if (!file.type.startsWith('image/')) {
return 'කරුණාකර image file එකක් upload කරන්න';
}
if (file.size > 5 * 1024 * 1024) {
return 'Images 5MB ට අඩු විය යුතුය';
}
}

if (category === 'document') {
if (file.size > 10 * 1024 * 1024) {
return 'Documents 10MB ට අඩු විය යුතුය';
}
}

return true;
},
],
});

return (
<div>
<div style={{ marginBottom: 20 }}>
<label>
<input
type="radio"
value="image"
checked={category === 'image'}
onChange={() => setCategory('image')}
/>
Images (උපරිම 5MB)
</label>
<label style={{ marginLeft: 20 }}>
<input
type="radio"
value="document"
checked={category === 'document'}
onChange={() => setCategory('document')}
/>
Documents (උපරිම 10MB)
</label>
</div>

<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>
{category === 'image' ? 'images' : 'documents'} මෙතැනට දමන්න
</p>
</div>
</div>
);
}

Virus/Malware Scanning

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

function MalwareScanUploader() {
const { files, state, actions, getDropProps, getInputProps } = useDropup({
customRules: [
// External service සමඟ ගොනු scan කරන්න
async (file) => {
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 හඳුනාගත්: ${threat}`;
}

return true;
} catch (error) {
return 'ගොනුව scan කළ නොහැකි විය. කරුණාකර නැවත උත්සාහ කරන්න.';
}
},
],

onValidationError: (errors) => {
errors.forEach(({ file, errors }) => {
console.error(`${file.name} ප්‍රතික්ෂේප විය:`, errors);
});
},
});

return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>ගොනු upload කිරීමට පෙර malware සඳහා scan වේ</p>
</div>
);
}

Pre-built Validation Rules

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

function PrebuiltRulesUploader() {
const { files, getDropProps, getInputProps } = useDropup({
customRules: [
// Built-in rules
commonRules.noExecutables, // .exe, .bat, etc. block කරන්න
commonRules.noHiddenFiles, // . න් ආරම්භ වන ගොනු block කරන්න
commonRules.maxFilenameLength(50), // උපරිම 50 chars
commonRules.allowedExtensions(['.jpg', '.png', '.pdf']),

// Custom rules සමඟ ඒකාබද්ධ කරන්න
(file) => {
if (file.name.toLowerCase().includes('temp')) {
return 'Temporary ගොනු අවසර නැත';
}
return true;
},
],
});

return (
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>දැඩි file validation සක්‍රීයයි</p>
</div>
);
}

Validation Error Display

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 characters)';
}
return true;
},
],

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

// තත්පර 5 කට පසු clear කරන්න
setTimeout(() => setValidationErrors([]), 5000);
},
});

return (
<div>
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>Images 3ක් දක්වා දමන්න (සෑම එකක් 5MB ට අඩු)</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>
)}

{/* පිළිගත් ගොනු */}
{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,
},
};