File type validation with Javascript

前些時候寫的簡單版測試程式,在表單送出前用 JavaScript 檢查檔案副檔名。當然這只是第一步驗證,在 PHP 端還是要對 Content Type 做一次檢查。

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>File Type Validation in JavaScript. ver 0.1</title>
    </head>
<body>

<form method="post" enctype="multipart/form-data" onsubmit="return checkAllFile();";>
    <input class="file-selector" type="file" name="userfile1" size="20"/></br>
    <input class="file-selector" type="file" name="userfile2" size="20"/></br>
    <input class="file-selector" type="file" name="userfile3" size="20"/></br>
    <input class="file-selector" type="file" name="userfile4" size="20"/></br>
    <input class="file-selector" type="file" name="userfile5" size="20"/></br>
    <input type="submit" value="upload"/>
</form>

<script type="text/javascript">
function checkAllFile(){
    var node_list = document.getElementsByTagName('input');
    var num_of_not_allowed_files = 0;

    for (var i = 0; i < node_list.length; i++){
        var node = node_list[i];
        if(node.getAttribute('type') == 'file'){
            var type = node.value;
            console.log(type);
            switch(type.substring(type.lastIndexOf('.') + 1).toLowerCase()){
                case 'gif': case 'jpg': case 'png':
                    //alert("an image");
                    // Do Nothing.
                    break;
                default:
                    num_of_not_allowed_files++;
                    break;
            }
        }
    }
    console.log('num_of_not_allowed_files: ' + num_of_not_allowed_files);
    if(num_of_not_allowed_files > 0){
        alert('檔案格式錯誤,只能上傳圖片哦');
        return false;
    } else return true;
}
</script>

</body>
</html>

ps. 這並不是一份最佳化過的程式碼,僅供參考。


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version