カスタム検証
アップロード用の洗練された検証ルールを作成します。
基本的なカスタムルール
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>
);
}
// ファイルハッシュを計算するヘルパー関数
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,
},
};