تخطي إلى المحتوى الرئيسي

التحقق المخصص

إنشاء قواعد تحقق متطورة لرفع الملفات.

قواعد مخصصة أساسية

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

function CustomValidationUploader() {
const { files, getDropProps, getInputProps } = useDropup({
customRules: [
// القاعدة 1: فحص اسم الملف
(file) => {
if (file.name.includes(' ')) {
return 'أسماء الملفات لا يمكن أن تحتوي على مسافات';
}
return true;
},

// القاعدة 2: فحص الامتداد
(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: [
// التحقق من التكرار على الخادم
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;
},

// التحقق من محتوى الملف
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>
);
}

// دالة مساعدة لحساب 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: [
// التحقق من أبعاد الصورة الفعلية
async (file) => {
if (!file.type.startsWith('image/')) return true;

const dimensions = await getImageDimensions(file);

if (dimensions.width < 200 || dimensions.height < 200) {
return 'يجب أن تكون الصورة 200×200 بكسل على الأقل';
}

if (dimensions.width > 4000 || dimensions.height > 4000) {
return 'الصورة لا يمكن أن تتجاوز 4000×4000 بكسل';
}

return true;
},

// التحقق من نسبة العرض إلى الارتفاع
async (file) => {
if (!file.type.startsWith('image/')) return true;

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

// تتطلب صور مربعة تقريباً (نسبة 0.8 إلى 1.2)
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>
);
}

// دالة مساعدة للحصول على أبعاد الصورة
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({
// قبول ديناميكي بناءً على الفئة
accept: category === 'image'
? 'image/*'
: category === 'document'
? '.pdf,.doc,.docx'
: '*/*',

customRules: [
(file) => {
// تحقق خاص بالفئة
if (category === 'image') {
if (!file.type.startsWith('image/')) {
return 'يرجى رفع ملف صورة';
}
if (file.size > 5 * 1024 * 1024) {
return 'يجب أن تكون الصور أقل من 5MB';
}
}

if (category === 'document') {
if (file.size > 10 * 1024 * 1024) {
return 'يجب أن تكون المستندات أقل من 10MB';
}
}

return true;
},
],
});

return (
<div>
<div style={{ marginBottom: 20 }}>
<label>
<input
type="radio"
value="image"
checked={category === 'image'}
onChange={() => setCategory('image')}
/>
صور (الحد الأقصى 5MB)
</label>
<label style={{ marginLeft: 20 }}>
<input
type="radio"
value="document"
checked={category === 'document'}
onChange={() => setCategory('document')}
/>
مستندات (الحد الأقصى 10MB)
</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: [
// فحص الملف باستخدام خدمة خارجية
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 `تم اكتشاف برنامج ضار: ${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: [
// قواعد مدمجة
commonRules.noExecutables, // حظر .exe، .bat، إلخ.
commonRules.noHiddenFiles, // حظر الملفات التي تبدأ بـ .
commonRules.maxFilenameLength(50), // الحد الأقصى 50 حرف
commonRules.allowedExtensions(['.jpg', '.png', '.pdf']),

// دمج مع قواعد مخصصة
(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);

// مسح بعد 5 ثوانٍ
setTimeout(() => setValidationErrors([]), 5000);
},
});

return (
<div>
<div {...getDropProps()} style={styles.dropzone}>
<input {...getInputProps()} />
<p>أفلت حتى 3 صور (الحد الأقصى 5MB لكل ملف)</p>
</div>

{/* أخطاء التحقق */}
{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,
},
};