File extension validation using javascript in MVC

This is article which demonstrate the validation of allowed file extension for upload of files in MVC using javascript. In this article i have used validation for valid image format like Jpeg, Jpg,Gif and png image format. If users ties to upload any other file apart from above mentioned file then the javascript function will shows proper message to user to select appropriate files.

I have used html input file control for uploading of files in MVC application.

following is the html code for it.


<body>
    <div style="height:50px; padding-bottom:20px;">
      @using (@Html.BeginForm("Create","FileUpload",FormMethod.Post,new{ enctype = "multipart/form-data"}))
{

<input type="file" id="file1" name="sdf" style=" margin-top:0px;" onchange="if( CheckExtention(this.value) ) {parent.ShowHideImage(true);this.form.submit();}" />



}
  
    </div>
</body>

and following is the javascript code to implement the validation


<script type="text/javascript">
  

    function CheckExtention(file)
    {
 var ext=  file.substr(file.lastIndexOf('.'),4).toLowerCase();
 
    if(ext!='.jpg' && ext!='.png' && ext!='.jpeg' && ext!=".gif")
    {
        alert('Only Jpg,png,Jpeg,or gif format allowed');
        
        var file = document.getElementById("file1");
        file.value = "";
        return false;

    }
    else 
    {
        return true;
    }

    }

</script>

I hope all you guys understood the concept.

Kindly let me know if you have any queries

Comments