How can the file extension be validated in an input type file using JQuery?

后端 未结 4 1197
后悔当初
后悔当初 2021-01-22 02:35

HTML:


Rule: The file to

相关标签:
4条回答
  • 2021-01-22 02:48

    See here: get the filename of a fileupload in a document through javascript on how to get the filename:

    var extension = $('#group_documents_file').val().match(/[^.]+$/).pop().toLowerCase();
    

    This should get you anything after the period in the filename.

    EDIT:

    If you don't want to use a regEx, I would recommend using split, with pop:

    var extension = $('#group_documents_file').val().split('.').pop().toLowerCase();
    

    Then, to check for allowed extensions, do the following:

    if ( ~$.inArray(extension, ['jpg', 'jpeg', 'gif', 'png']) ) {
        // correct file type...
    } else {
        // incorrect file type...
    }
    
    0 讨论(0)
  • 2021-01-22 02:51

    You simply need to pull the value of the element:

    var fileName = $('#group_document_file').val();
    
    var extension = fileName.slice('.')[fileName.slice('.').length - 1].toLowerCase();
    
    if(extension == 'jpeg' || extension == 'gif' || extension == 'png')
       // Show Validated Image
    else
       alert('Choose a supported image format');
    
    0 讨论(0)
  • 2021-01-22 02:57

    The following gets the extension of the file:

    JS:

    $('#group_documents_file').change(function(){
        var value = this.value;
        val = value.split("\\");
        var file = (val[val.length - 1]).split('.');
        var ext = file[file.length - 1];
        alert(ext);
    })
    

    Fiddle: http://jsfiddle.net/maniator/gveqX/

    0 讨论(0)
  • 2021-01-22 03:04

    Try this

    var fName = $('#group_document_file').val();
    
    var validExtns ["jpg", "gif", "png"];
    
    var extn = fName.slice('.')[fName.slice('.').length - 1];
    
    if($.inArray(extn.toLowerCase(), validExtns) != -1){
       // Show Validated Image
    }
    else{
       alert('Invalid image format');
    }
    
    0 讨论(0)
提交回复
热议问题