13

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>
1
  • 1
    as SLaks points out, you'll reject myfile.Gif because of casing. Commented Nov 22, 2011 at 17:39

11 Answers 11

29

var fname = "the file name here.ext";
var re = /(\.jpg|\.jpeg|\.bmp|\.gif|\.png)$/i;
if (!re.exec(fname)) {
  alert("File extension not supported!");
}

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

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.

Comments

2

The return value of the submit handler affects the submission.

onsubmit="return Checkfiles();"

This is basically saying:

form.onsubmit = function () { return Checkfiles(); };

Comments

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!");
}

Comments

1

You need to return CheckFiles()

Comments

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;
} 

});

Comments

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);
            }
    });

Comments

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()

Comments

0

I know this is a very old question but here is an answer for new developers who are facing the same issue.

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

<script type="text/javascript">
    function Checkfiles(event) {
        event.preventDefault();
        var form = document.getElementsByTagName('form')[0];
        var fup = document.getElementById('filename');
        var fileName = fup.value;\
        var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
        if(ext.toLowerCase() === 'gif') {
            form.submit();
            return true;
        } else {
            alert("Upload Gif Images only");            
            return false;
        } 
    }
</script>

Comments

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;
    } 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.