Tuesday, 30 May 2023

javascript file validation on submit

<form onsubmit="checkFileExist(event)" > 


function checkFileExist(event) {

    var fileInput = document.getElementById('validatedCustomFile');

    var file = fileInput.files[0];


    if (!file) {

        event.preventDefault(); // Prevent form submission

        $('.file-error').text('File is required');

        return false;

    }


    // File extension validation

    var allowedExtensions = ['.jpg', '.jpeg', '.png']; // Add your allowed file extensions here

    var fileExtension = file.name.split('.').pop().toLowerCase();

    if (!allowedExtensions.includes('.' + fileExtension)) {

        event.preventDefault(); // Prevent form submission

        $('.file-error').text('Invalid file extension. Only JPG, JPEG, and PNG files are allowed.');

        return false;

    }


    // File size validation

    var maxSizeInBytes = 200 * 1024; // 200 KB (200 * 1024 bytes)

    if (file.size > maxSizeInBytes) {

        event.preventDefault(); // Prevent form submission

        $('.file-error').text('File size exceeds the limit of 200 KB');

        return false;

    }


    // Additional validation or actions can be performed here

}


Laravel Export data to csv

 use Illuminate\Http\Response; // Define a function to export data to CSV function exportToCSV($exportData, $columns) {     $filename = ...