Subscribe to Youtube channel

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

Popular posts from this blog

Root your Gingerbread 2.3.4 android Mobile Phone

Restore the lost focus of Auto post back controls in asp.net update Panel control

Disable backspace key using Jquery

Implement Logging in CSV file using Nlog in .net core MVC application- part 2

Implement Nlog in .Net core MVC application part 1

Angular User Session Timeout example step by step

Devexpress Datebox date formatting in angular 6 with example

How to Import CSV File and bind csv file data to gridview in asp.net using c#

Add Comma automatically while entering amounts in textbox using Javascript