File Upload with Image Preview

htmlnextjs

Avatar Upload Validation

Uploading a file only to have the server reject it wastes time and bandwidth. With validateFile(), you can validate the selected file immediately—checking its type, size, and image dimensions before generating a preview or submitting the form.


HTML

<form id="profileForm">
    <input
        type="file"
        name="avatar"
        accept="image/png,image/jpeg"
    />

    <div id="avatarError"></div>

    <img
        id="preview"
        style="display:none; max-width:120px;"
        alt="Avatar Preview"
    />
</form>

JavaScript

import NFSFU234FormValidation from "@nfsfu234/form-validation";

const validator = new NFSFU234FormValidation({
    form: "profileForm"
});

const avatarInput = document.querySelector(
    '[name="avatar"]'
);

const preview = document.getElementById("preview");
const error = document.getElementById("avatarError");

avatarInput.addEventListener("change", async () => {

    const result = await validator.validateFile(
        avatarInput,
        {
            required: true,

            accept: [
                "image/png",
                "image/jpeg"
            ],

            maxSizeMB: 2,

            maxWidth: 1000,
            maxHeight: 1000
        }
    );

    if (result !== true) {

        error.textContent = result.message;

        preview.style.display = "none";

        preview.removeAttribute("src");

        return;
    }

    error.textContent = "";

    preview.src = URL.createObjectURL(
        avatarInput.files[0]
    );

    preview.style.display = "block";
});

What happens?

Every time the user selects a file, the library automatically validates it before anything else happens.

The validation checks:

  • The field is not empty (when required is enabled).
  • The file type matches the allowed formats.
  • The file size is within the configured limit.
  • Image dimensions stay within the allowed width and height.

Only after every check succeeds is the preview displayed.


Validation Rules

await validator.validateFile(fileInput, {
    required: true,

    accept: [
        "image/png",
        "image/jpeg"
    ],

    maxSizeMB: 2,

    maxWidth: 1000,
    maxHeight: 1000
});

You can also use:

minWidth
minHeight

to enforce minimum image dimensions.


Why validate before previewing?

Generating a preview for an invalid file creates a confusing user experience.

A user could briefly see an image before immediately being told it isn't allowed.

Validating first means:

  • Invalid files never appear.
  • Users receive feedback immediately.
  • No unnecessary uploads occur.
  • The interface stays consistent.

Important

validateFile() is asynchronous because image dimensions cannot be determined until the browser has decoded the selected file.

Always use:

const result = await validator.validateFile(...);

instead of calling it synchronously.


Continue learning

File Upload with Image Preview | NFSFU234FormValidation