| 1 |
By providing `validator` prop you can specify custom validation for files. |
| 2 |
|
| 3 |
The value must be a function that accepts File object and returns null if file should be accepted or error object/array of error objects if file should be rejected. |
| 4 |
|
| 5 |
```jsx harmony |
| 6 |
import React from 'react'; |
| 7 |
import {useDropzone} from 'react-dropzone'; |
| 8 |
|
| 9 |
const maxLength = 20; |
| 10 |
|
| 11 |
function nameLengthValidator(file) { |
| 12 |
if (file.name.length > maxLength) { |
| 13 |
return { |
| 14 |
code: "name-too-large", |
| 15 |
message: `Name is larger than ${maxLength} characters` |
| 16 |
}; |
| 17 |
} |
| 18 |
|
| 19 |
return null |
| 20 |
} |
| 21 |
|
| 22 |
function CustomValidation(props) { |
| 23 |
const { |
| 24 |
acceptedFiles, |
| 25 |
fileRejections, |
| 26 |
getRootProps, |
| 27 |
getInputProps |
| 28 |
} = useDropzone({ |
| 29 |
validator: nameLengthValidator |
| 30 |
}); |
| 31 |
|
| 32 |
const acceptedFileItems = acceptedFiles.map(file => ( |
| 33 |
<li key={file.path}> |
| 34 |
{file.path} - {file.size} bytes |
| 35 |
</li> |
| 36 |
)); |
| 37 |
|
| 38 |
const fileRejectionItems = fileRejections.map(({ file, errors }) => ( |
| 39 |
<li key={file.path}> |
| 40 |
{file.path} - {file.size} bytes |
| 41 |
<ul> |
| 42 |
{errors.map(e => ( |
| 43 |
<li key={e.code}>{e.message}</li> |
| 44 |
))} |
| 45 |
</ul> |
| 46 |
</li> |
| 47 |
)); |
| 48 |
|
| 49 |
return ( |
| 50 |
<section className="container"> |
| 51 |
<div {...getRootProps({ className: 'dropzone' })}> |
| 52 |
<input {...getInputProps()} /> |
| 53 |
<p>Drag 'n' drop some files here, or click to select files</p> |
| 54 |
<em>(Only files with name less than 20 characters will be accepted)</em> |
| 55 |
</div> |
| 56 |
<aside> |
| 57 |
<h4>Accepted files</h4> |
| 58 |
<ul>{acceptedFileItems}</ul> |
| 59 |
<h4>Rejected files</h4> |
| 60 |
<ul>{fileRejectionItems}</ul> |
| 61 |
</aside> |
| 62 |
</section> |
| 63 |
); |
| 64 |
} |
| 65 |
|
| 66 |
<CustomValidation /> |
| 67 |
``` |
| 68 |
|