12

I have a question regarding to JavaScript validation. I am validaing the <input type="file"> whenever my scripts runs, it validates but also the action page is called. I want to stop the action page until the validation is complete. Here is my code, any help will be awesome. Regards

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Image Uploading</title>
    </head>


    <body>
        <form name="xx" action="server.php" method="post" enctype="multipart/form-data" onsubmit="Checkfiles(this)">
            <input type="file" name="file_uploading" id="filename">
            <input type="submit" value="Submit" name="uploadfile">
        </form>

        <form name="view" method="post">
            <a href="view_server.php">View your uploaded Images</a>
        </form>
    </body>
</html>

<script type="text/javascript">
    function Checkfiles() {
        var fup = document.getElementById('filename');
        var fileName = fup.value;
        var ext = fileName.substring(fileName.lastIndexOf('.') + 1);

        if(ext =="GIF" || ext=="gif") {
            return true;
        } else {
            alert("Upload Gif Images only");
            return false;
        }
    }
</script>
iconoclast
  • 21,213
  • 15
  • 102
  • 138
Zain
  • 5,391
  • 11
  • 34
  • 34

10 Answers10

27

var fname = "the file name here.ext";
var re = /(\.jpg|\.jpeg|\.bmp|\.gif|\.png)$/i;
if (!re.exec(fname)) {
  alert("File extension not supported!");
}
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
MOHW
  • 737
  • 1
  • 11
  • 23
3

File Extension Validation through javascript

function ValidateExtension() {
        var allowedFiles = [".doc", ".docx", ".pdf"];
        var fileUpload = document.getElementById("fileUpload");
        var lblError = document.getElementById("lblError");
        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
        if (!regex.test(fileUpload.value.toLowerCase())) {
            lblError.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.";
            return false;
        }
        lblError.innerHTML = "";
        return true;
    }

onclick event of submit button call this javascript function.

With the help of ID = lblError , print the error message in html section.

2

In general, you can use JavaScript some() method for that.

function isImage(icon) {
  const ext = ['.jpg', '.jpeg', '.bmp', '.gif', '.png', '.svg'];
  return ext.some(el => icon.endsWith(el));
}

const fname = "filename.ext";
if (!isImage(fname)) {
  console.log("File extension not supported!");
}
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
2

The return value of the submit handler affects the submission.

onsubmit="return Checkfiles();"

This is basically saying:

form.onsubmit = function () { return Checkfiles(); };
J. K.
  • 8,268
  • 1
  • 36
  • 35
2

You can use the File Api to test for magic number. Maybe take a look at this answer for other ideas about the validation. More reliable than the file extension check.

Community
  • 1
  • 1
Bakudan
  • 19,134
  • 9
  • 53
  • 73
1

Upload bulk data through excel sheet(.csv)

$("form").submit(function(){
 var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(csv)$");
if(!(regex.test(val))) {
$(this).val('');
alert('Only csv file can be uploaded');
return false;
} 

});
Rajnesh Thakur
  • 326
  • 1
  • 3
  • 8
1
var _URL = window.URL || window.webkitURL;
    $("input[type=file]").change(function(e) {
        var file;
            if ((file = this.files[0])) {
                var img = new Image();
                img.onload = function () {
                    // do to on load
                };
                img.onerror = function () {
                    alert("valid format " + file.type);
                };
                img.src = _URL.createObjectURL(file);
            }
    });
1

The fileValidation() function contains the complete file type validation code. This JavaScript function needs to call for file extension validation.

HTML

<!-- File input field -->
<input type="file" id="file" onchange="return fileValidation()"/>

<!-- Image preview -->
<div id="imagePreview"></div>

JavaScript

function fileValidation(){
    var fileInput = document.getElementById('file');
    var filePath = fileInput.value;
    var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
    if(!allowedExtensions.exec(filePath)){
        alert('Please upload file having extensions .jpeg/.jpg/.png/.gif only.');
        fileInput.value = '';
        return false;
    }else{
        //Image preview
        if (fileInput.files && fileInput.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('imagePreview').innerHTML = '<img src="'+e.target.result+'"/>';
            };
            reader.readAsDataURL(fileInput.files[0]);
        }
    }
}

fileValidation()
MD SHAYON
  • 7,001
  • 45
  • 38
1

You need to return CheckFiles()

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0
> html
 <input type="file" id="userfile" name="userfile" value="" class="form-control userfile" required>

> javascript
                       $(document).on('change', '.userfile', function (e) {
                        e.preventDefault();
                        const thisValue = $(this).val().split('.').pop().toLowerCase();
                        const userFile = [thisValue];
                        // Allowing file type
                        const validFile = ['csv', 'xlsx'];
                        // const intersection = validFile.filter(element => userFile.includes(element));
                        // if(intersection == ''){
                        //     $(this).val('');
                        //     alert('Please Select ' + validFile + ' file');
                        //     return false;
                        // }

                        

                       // Allowing file type
                        const allowedExtensions =  /(\.csv|\.xlsx)$/i;
                        if (!allowedExtensions.exec($(this).val())) {
                            $(this).val('');
                            alert('Please Select ' + validFile + ' file');
                            return false;
                        } 
                    });