Input type File validation – Client side

Thinking of allowing only specific file types to be browsed through File Input HTML field??

Here’ a simple regex based javascript that can help you out with the solution. It’s based on the file extension of file being browsed and clears the input field if validation fails. The allowed list of file extensions is exhaustive and can be changed as per the requirement. Since, its a client side validation, you need to complement it with server side validation as a practice.

$(document).ready(function () {	
	$('input[type=file]').change(function () {
		var val = $(this).val().toLowerCase();   
		var regex  =  new RegExp("(.*?).(jpg|jpeg|txt|png|docx|gif|doc|pdf|xml|bmp|ppt|pptx|vsd|xls|xlt|xlsx)$");
			alert('Incorrect file selected!!');

Note: You need to include jQuery (mentioned below) to your page for leveraging this code in HEAD section of HTML.

<script type="text/javascript" src=""></script>


(Visited 84 times, 1 visits today)