表单提交时检查文件类型?

时间:2022-11-24 14:22:31

I have the form having the follwing fields,

我的表格有以下字段,

<form onsubmit="return checkcreateform()" action="/gallery/create" method="post" enctype="multipart/form-data">
   <label>Type:*</label>
    <label for="type-1">
     <input type="radio" checked="checked" value="1" id="type-1" name="type">Image
    </label>
   <br>
   <label for="type-2">
   <input type="radio" value="2" id="type-2" name="type">Video
   </label>  
   <label class="itemdetailfloatL required" for="file">File:*</label>
   <input type="hidden" id="MAX_FILE_SIZE" value="8388608" name="MAX_FILE_SIZE">
   <input type="file" tabindex="5" class="text-size text" id="file" name="file">
 <input type="submit" value="Create" id="submit" name="submit">
</form>

I want to validate before form submit. Here how can i validate if user select type as Image and upload video or select type as video and upload image ?

我想在表单提交之前验证。在这里我如何验证用户选择类型为图像并上传视频或选择类型为视频和上传图像?

We can achieve this by javascript or jquery.Any quick way to validate this ?

我们可以通过javascript或jquery实现这一点。快速验证这个方法吗?

Kindly help me on this.

请帮助我。

5 个解决方案

#1


45  

Instead of using onsubmit, use jQuery's submit handler, and validate using some javascript like the following:

而不是使用onsubmit,使用jQuery的提交处理程序,并使用如下的一些JavaScript进行验证:

function getExtension(filename) {
    var parts = filename.split('.');
    return parts[parts.length - 1];
}

function isImage(filename) {
    var ext = getExtension(filename);
    switch (ext.toLowerCase()) {
    case 'jpg':
    case 'gif':
    case 'bmp':
    case 'png':
        //etc
        return true;
    }
    return false;
}

function isVideo(filename) {
    var ext = getExtension(filename);
    switch (ext.toLowerCase()) {
    case 'm4v':
    case 'avi':
    case 'mpg':
    case 'mp4':
        // etc
        return true;
    }
    return false;
}

$(function() {
    $('form').submit(function() {
        function failValidation(msg) {
            alert(msg); // just an alert for now but you can spice this up later
            return false;
        }

        var file = $('#file');
        var imageChosen = $('#type-1').is(':checked');
        if (imageChosen && !isImage(file.val())) {
            return failValidation('Please select a valid image');
        }
        else if (!imageChosen && !isVideo(file.val())) {
            return failValidation('Please select a valid video file.');
        }

        // success at this point
        // indicate success with alert for now
        alert('Valid file! Here is where you would return true to allow the form to submit normally.');
        return false; // prevent form submitting anyway - remove this in your environment
    });

});

jsFiddle version here, tested in IE8, RockMelt (based on Chrome) and Firefox 7: http://jsfiddle.net/Ngrbj/4/

这里有jsFiddle版本,在IE8,RockMelt(基于Chrome)和Firefox 7上测试过:http://jsfiddle.net/Ngrbj/4/

#2


5  

The answer provided works, but something that will run a little faster with a lot fewer lines for the validation code, using javascript array functions:

提供的答案是有效的,但使用javascript数组函数,使用更少的验证代码行运行得更快一些:

var extensionLists = {}; //Create an object for all extension lists
extensionLists.video = ['m4v', 'avi','mpg','mp4', 'webm'];  
extensionLists.image = ['jpg', 'gif', 'bmp', 'png'];

// One validation function for all file types    
function isValidFileType(fName, fType) {
    return extensionLists[fType].indexOf(fName.split('.').pop()) > -1;
}

Then, the if statement in the submit code is just swapped with:

然后,提交代码中的if语句刚刚与:

if (imageChosen && !isValidFileType(file.val(), 'image')) {
        return failValidation('Please select a valid image');
    }
else if (!imageChosen && !isValidFileType(file.val(), 'video')) {
        return failValidation('Please select a valid video file.');
    }        

#3


2  

Using files property on input:file you can loop through file objects and check type property

在input:file上使用files属性,您可以遍历文件对象并检查type属性

    $('#upload').on("change", function(){
 
         var  sel_files  = document.getElementById('upload').files;
         var len = sel_files.length;
 
         for (var i = 0; i < len; i++) {

            var file = sel_files[i];
         
            if (!(file.type==='application/pdf')) {
            continue;
            }
          }

      }); 
<div class="modal">
  <form id="form-upload">
    <input type="file" name="upload" id="upload" multiple>
    <br/>
     
</form>
</div>

#4


0  

you can try this:

你可以试试这个:

function getFile(fieldId) {
    var fileInsert = document.getElementById(fieldId).value;
        fileName = fileName.split('/');
        fileName = fileName[fileName.length];
        extentions = fileName.split('.');
        extentions = extentions[extentions.length];
    return extentions;
}

You can use this function in your checkcreateform()

您可以在checkcreateform()中使用此功能

#5


0  

First you should change your html like this:

首先,您应该像这样更改您的HTML:

<input type="file" tabindex="5" class="text-size text" id="file" name="file" onchange="checkeExtension(this.value,"submit");">

Then, you need a function like this:

然后,你需要一个这样的函数:

///image 1 and video 2
//you can extend file types
var types= {
    'jpg' :"1",
    'avi' :"2",
    'png' :"1",
    "mov" : "2",
}

function checkeExtension(filename,submitId) {
    var re = /\..+$/;
    var ext = filename.match(re);
    var type = $("input[type='radio']:checked").val();
    var submitEl = document.getElementById(submitId);

    if (types[ext] == type) {
        submitEl.disabled = false;
        return true;
    } else {
        alert("Invalid file type, please select another file");
        submitEl.disabled = true;
        return false;
    }  
}

#1


45  

Instead of using onsubmit, use jQuery's submit handler, and validate using some javascript like the following:

而不是使用onsubmit,使用jQuery的提交处理程序,并使用如下的一些JavaScript进行验证:

function getExtension(filename) {
    var parts = filename.split('.');
    return parts[parts.length - 1];
}

function isImage(filename) {
    var ext = getExtension(filename);
    switch (ext.toLowerCase()) {
    case 'jpg':
    case 'gif':
    case 'bmp':
    case 'png':
        //etc
        return true;
    }
    return false;
}

function isVideo(filename) {
    var ext = getExtension(filename);
    switch (ext.toLowerCase()) {
    case 'm4v':
    case 'avi':
    case 'mpg':
    case 'mp4':
        // etc
        return true;
    }
    return false;
}

$(function() {
    $('form').submit(function() {
        function failValidation(msg) {
            alert(msg); // just an alert for now but you can spice this up later
            return false;
        }

        var file = $('#file');
        var imageChosen = $('#type-1').is(':checked');
        if (imageChosen && !isImage(file.val())) {
            return failValidation('Please select a valid image');
        }
        else if (!imageChosen && !isVideo(file.val())) {
            return failValidation('Please select a valid video file.');
        }

        // success at this point
        // indicate success with alert for now
        alert('Valid file! Here is where you would return true to allow the form to submit normally.');
        return false; // prevent form submitting anyway - remove this in your environment
    });

});

jsFiddle version here, tested in IE8, RockMelt (based on Chrome) and Firefox 7: http://jsfiddle.net/Ngrbj/4/

这里有jsFiddle版本,在IE8,RockMelt(基于Chrome)和Firefox 7上测试过:http://jsfiddle.net/Ngrbj/4/

#2


5  

The answer provided works, but something that will run a little faster with a lot fewer lines for the validation code, using javascript array functions:

提供的答案是有效的,但使用javascript数组函数,使用更少的验证代码行运行得更快一些:

var extensionLists = {}; //Create an object for all extension lists
extensionLists.video = ['m4v', 'avi','mpg','mp4', 'webm'];  
extensionLists.image = ['jpg', 'gif', 'bmp', 'png'];

// One validation function for all file types    
function isValidFileType(fName, fType) {
    return extensionLists[fType].indexOf(fName.split('.').pop()) > -1;
}

Then, the if statement in the submit code is just swapped with:

然后,提交代码中的if语句刚刚与:

if (imageChosen && !isValidFileType(file.val(), 'image')) {
        return failValidation('Please select a valid image');
    }
else if (!imageChosen && !isValidFileType(file.val(), 'video')) {
        return failValidation('Please select a valid video file.');
    }        

#3


2  

Using files property on input:file you can loop through file objects and check type property

在input:file上使用files属性,您可以遍历文件对象并检查type属性

    $('#upload').on("change", function(){
 
         var  sel_files  = document.getElementById('upload').files;
         var len = sel_files.length;
 
         for (var i = 0; i < len; i++) {

            var file = sel_files[i];
         
            if (!(file.type==='application/pdf')) {
            continue;
            }
          }

      }); 
<div class="modal">
  <form id="form-upload">
    <input type="file" name="upload" id="upload" multiple>
    <br/>
     
</form>
</div>

#4


0  

you can try this:

你可以试试这个:

function getFile(fieldId) {
    var fileInsert = document.getElementById(fieldId).value;
        fileName = fileName.split('/');
        fileName = fileName[fileName.length];
        extentions = fileName.split('.');
        extentions = extentions[extentions.length];
    return extentions;
}

You can use this function in your checkcreateform()

您可以在checkcreateform()中使用此功能

#5


0  

First you should change your html like this:

首先,您应该像这样更改您的HTML:

<input type="file" tabindex="5" class="text-size text" id="file" name="file" onchange="checkeExtension(this.value,"submit");">

Then, you need a function like this:

然后,你需要一个这样的函数:

///image 1 and video 2
//you can extend file types
var types= {
    'jpg' :"1",
    'avi' :"2",
    'png' :"1",
    "mov" : "2",
}

function checkeExtension(filename,submitId) {
    var re = /\..+$/;
    var ext = filename.match(re);
    var type = $("input[type='radio']:checked").val();
    var submitEl = document.getElementById(submitId);

    if (types[ext] == type) {
        submitEl.disabled = false;
        return true;
    } else {
        alert("Invalid file type, please select another file");
        submitEl.disabled = true;
        return false;
    }  
}