Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File type validation with JavaScript

Tags:

javascript

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>
like image 220
Zain Avatar asked Nov 22 '11 17:11

Zain


2 Answers

var fname = "the file name here.ext";
var re = /(\.jpg|\.jpeg|\.bmp|\.gif|\.png)$/i;
if (!re.exec(fname)) {
  alert("File extension not supported!");
}
like image 193
MOHW Avatar answered Oct 25 '22 06:10

MOHW


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!");
}
like image 35
Penny Liu Avatar answered Oct 25 '22 05:10

Penny Liu