커스텀 유효성 검사
업로드를 위한 정교한 유효성 검사 규칙을 만듭니다.
기본 커스텀 규칙
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,
},
};