How to Validate File or File type in Java Script MVC

Programmer need to check whether the file is selected by the user or not, when uploading a file. If user will not upload any file and submit the form, the code will throw an exception with description like "file must not be null".

To overcome this issue programmer have to check the uploaded file before the form submission, and this can be performed by using Java script. Write the following code in our view where the file upload control is placed:

function validateForm() {
if ($("#file").val() == "") {
alert("Please select a file");
return false;

Here “#file” is the id of file upload control and we are checking the value of this control. If the value is empty then it will alert with the message shown and return back to the form. If this control will have file then it will submit the form. On the submit button, just call this function to execute this code with Onclick=”validateForm();”.

Now to select only some file types write another function as below:

function checkfile(sender) {
        var validExts = new Array(".jpeg", ".jpg", ".png");
        var fileExt = sender.value;
        fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
        if (validExts.indexOf(fileExt) < 0) {
            alert("File must of types \".jpeg\", \".jpg\", \".png\");
            return false;
        else return true;

This function will be called on OnChange event of the file upload control. It will show an alert message written above if the type of selected file will not be in the list declared in the function. Write CheckFile(this) in onChange event of the file upload control.

In this function we are checking only the extension of the selected file, extension may be found by any individual logic. Earlier article was about to uploading file, this java script will not submit the form if user will not select any file through the file upload control.


Post a Comment