Go Back

1 min read

Validating Image File Extensions in JavaScript

profile

Nitin k

|

October 28, 2024

views

Handling file uploads requires validating file types to ensure only supported formats are allowed. Here's a simple utility function that checks if a file has a valid image extension.

JavaScript Snippet

validateImage.ts

How It Works:

  • Supported Extensions: The function checks common image formats like .jpg, .png, .svg, etc.
  • Validation Logic: It compares the file extension with the supported list and returns true if a match is found.

Example Usage

index.tsx

Why Use This?

  • Security: Prevents unsupported file types from being uploaded.
  • Customizable: Easily add or remove file extensions.

Conclusion

Validating file types is essential for secure file uploads. This function simplifies the process and ensures only valid image files are accepted. Customize it as needed to fit your application's requirements.