2011-11-02 11 views
11

我有具有follwing場的形式,表格提交時檢查文件類型?

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

我想驗證表單提交之前。在這裏,我如何驗證,如果用戶選擇類型作爲圖像和上傳視頻或選擇類型作爲視頻和上傳圖像?

我們可以通過JavaScript或jquery.Any快速的方法來驗證此實現這一目標?

請幫我在這。

+1

我使用jQuery驗證插件:http://bassistance.de/jquery-plugins/jquery-plugin-validation/ – Wayne

+1

有一個「接受」屬性即將上市,它不是真正支持的是,但看看:http://www.w3schools.com/jsref/prop_fileupload_accept.asp通常唯一安全有效的方法是使用serverside,但只需使用javascript或jQuery的validate插件檢查文件擴展名即可。 – adeneo

回答

39

而不是使用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版本在這裏,在IE8,RockMelt的測試(基於瀏覽器)和Firefox 7:http://jsfiddle.net/Ngrbj/4/

+0

感謝非常有幫助 – mymotherland

+2

用戶可以輕鬆地更改文件擴展名「傻瓜」這樣的驗證,基於MIME類型的解決方案會更好(雖然,我不知道如果這樣的存在,仍然在尋找它自己) – loostro

+0

請參閱http:/ /stackoverflow.com/questions/7395548/js-and-type-match-as-file-mime-type-need-advice – loostro

0

你可以試試這個:

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

您可以在checkcreateform()

0

第一次使用此功能,您應該改變你的HTML這樣的:

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

然後,你需要一個功能像這樣:

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

上輸入使用的文件屬性:文件,你可以遍歷文件對象和檢查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>

3

答案提供的作品,但東西,將運行一個小有很多較少的線驗證碼速度更快,使用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; 
} 

然後,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.'); 
    }