This post is relate to my previous post where I have showed you how to insert an image. The place that we have been provided to upload an image is same as uploading a file. So we as developers, have responsibility to validate that File Field by not letting others to upload any executable (*.exe) file to the server.
So today I am going to show you a simple JavaScript that check what you are trying to upload through the form. Here I only check the file extension and if it is a “.exe” file I am not allow them to upload that file to the database and the server. The interface is same as my earlier post which I have mentioned above. Following is the relevant code for that script. You have to include that code block within;
<script type=”text/javascript”>…</script>
Now we will see the code.
... function imageValidate(){ var str = document.form1.fileFieldImage.value; var lower = str.toLowerCase(); var newStr = lower.substring(lower.length-4, lower.length); //alert(newStr); if(newStr == ".exe"){ alert("You cannot upload executable files...!"); return (false); }else{ return (true); } } ...
Here I have used the name attribute to call the form elements in the JavaScript. As an example form1 is the name attribute of the form.
The logic I have used here is, first I get the value that the client has entered to the File Field/Image Field. Then I convert that whole string in to lower case. Next I substring it from end where the file extension is. I just wanted to take last four characters of the string and check whether it is equal to “.exe“. If it is an executable file the Submit function will not be work and give you an alert message.
So from where this JavaScript called in to action. I have chosen the Submit button. This is the code for that.
... input type="submit" name="buttonSubmit" id="buttonSubmit" value="Submit" onclick="javascript: return imageValidate()" ...
Todays’ fun time is over. Enjoy yourself 🙂