ข้ามไปยังเนื้อหาหลัก

การตรวจสอบแบบกำหนดเอง

สร้างกฎการตรวจสอบที่ซับซ้อนสำหรับการอัปโหลดของคุณ

กฎที่กำหนดเองพื้นฐาน

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>
);
}

การตรวจสอบแบบ Async

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 'รูปภาพต้องมีขนาดอย่างน้อย 200x200 พิกเซล';
}

if (dimensions.width > 4000 || dimensions.height > 4000) {
return 'รูปภาพไม่สามารถเกิน 4000x4000 พิกเซล';
}

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>วางรูปภาพสี่เหลี่ยมจัตุรัส (ต่ำสุด 200px, สูงสุด 4000px)</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 แบบไดนามิกตามหมวดหมู่
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,
},
};