Wednesday, 23 July 2014

jQuery validation for file type extension

jQuery validation for file type extension

<script type="text/javascript">
  $(function(){
    $('input#submit').click(function(){
      var file = $('input[type="file"]').val();
      var exts = ['doc','docx','rtf','odt'];
      // first check if file field has any value
      if ( file ) {
        // split file name at dot
        var get_ext = file.split('.');
        // reverse name to check extension
        get_ext = get_ext.reverse();
        // check file type is valid as given in 'exts' array
        if ( $.inArray ( get_ext[0].toLowerCase(), exts ) > -1 ){
          alert( 'Allowed extension!' );
        } else {
          alert( 'Invalid file!' );
        }
      }
    });
  });
</script>

No comments:

Post a Comment