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

后端 未结 4 1199
后悔当初
后悔当初 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...
    }
    

提交回复
热议问题