File type validation with Javascript

后端 未结 8 868
梦谈多话
梦谈多话 2020-12-09 22:52

I have a question regarding to JavaScript validation. I am validaing the whenever my scripts runs, it validates but also the action

相关标签:
8条回答
  • 2020-12-09 23:14
    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);
                }
        });
    
    0 讨论(0)
  • 2020-12-09 23:15

    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.

    0 讨论(0)
提交回复
热议问题