I am trying to validate the filetype that users upload onto my website by using a regex, it works client side but when i submit my form with a filetype other than what should pass the regex it still submits. Can someone please tell me what I'm doing wrong
or if there is a better way for filetype validation? My razor code for the page is as follows and all of the other validation I have implemented works as expected:
{
Page.Title = "Add Game";
//Variables
var GameName = Request["Name"];
var Tags = "";
var Gamefile = Request["file"];
//Name validation
Validation.Add("Name",
Validator.Required("Please give the game a name"),
Validator.Regex(@"^[A-Za-z0-9 _]*$", "The name must only contain letters, numbers, space and/or underscores."),
Validator.StringLength(
maxLength: 100,
errorMessage: "Name must be less than 100 characters")
);
//SWF file validation
Validation.Add("file",
Validator.Regex(@"^.*\.(swf|SWF)$", "Invalid filetype, you must upload a .swf flash file")
);
if(IsPost && Request.Files[0].ContentLength == 0){
ModelState.AddError("file", "You must choose a file");
}
try{
if (IsPost && Validation.IsValid() && ModelState.IsValid) {
var db = Database.Open("Surgestuff");
var gCat = "";
var fileData = Request.Files[0];
var fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName);
var fileSavePath = Server.MapPath("~/upload/" + fileName);
var AddBy = WebSecurity.CurrentUserName;
var mod = 0;
var count = 0;
gCat=Request["formCat"];
Gamefile = fileName;
if (Validation.IsValid()){
fileData.SaveAs(fileSavePath);
var SQLINSERT = "INSERT INTO Games (Name, file_path, Category, AddBy, Mod, Hits) " + "VALUES (@0, @1, @2, @3, @4, @5)";
db.Execute(SQLINSERT, GameName, Gamefile, gCat, AddBy, mod, count);
Response.Redirect("~/Games");
}
}
}
catch(HttpException ex){
ModelState.AddError("file", "File exceeds 10MB");
}
}
My multimedia major project: http://www.surgestuff.com | Please mark me as answer if I helped
If you would like to personally see what I'm talking about I have this live on my subdomain at
http://v3.surgestuff.com/Admin/AddGame and it requires you to be logged in so if you're too lazy i created an account with the credentials of
Username: test Password: asdf
As a test i uploaded a .swf file, which showed no client side errors and worked as expected. Then i tried uploading a .png, it showed the client side errors but still uploaded and added the info to the database.
My multimedia major project: http://www.surgestuff.com | Please mark me as answer if I helped
The Validation helpers don't work for file uploads. They only work for items that populate the Request.Form collection. File uploads populate the Request.Files collection. So you will have to validate separately:
if (IsPost && Path.GetExtension(Request.Files[0].FileName != ".swf"){
ModelState.AddError("file", "Invalid filetype, you must upload a .swf flash file");
}
But that didn't work either. So, I came here for help.
My multimedia major project: http://www.surgestuff.com | Please mark me as answer if I helped
Is there some way for me to validate the file size that users attempt to upload using server side validation. My try catch doesn't work to catch HttpExceptions so I tried with:
It is the point at which you first try to refence the file that any HttpException due to oversized payloads is thrown, so you should put any attempt to reference the actual file in a try-catch block:
try{
if(IsPost && Request.Files[0].ContentLength > 0){
if(!Path.GetExtension(Request.Files[0].FileName.ToLower()).Equals(".swf")){
ModelState.AddError("file", "Only Flash files allowed");
}
}
}
catch(HttpException ex){
ModelState.AddError("file", "Make sure your file is less than 10MB");
}
I have now moved all of my razor code inside the try catch block except it is my validation message that throws me the error: it says the error is the part in my form with
@Html.ValidationMessage("Name")
My multimedia major project: http://www.surgestuff.com | Please mark me as answer if I helped
mhcodner
Member
219 Points
86 Posts
Filetype validation regex not working
Dec 21, 2012 11:28 AM|LINK
I am trying to validate the filetype that users upload onto my website by using a regex, it works client side but when i submit my form with a filetype other than what should pass the regex it still submits. Can someone please tell me what I'm doing wrong or if there is a better way for filetype validation? My razor code for the page is as follows and all of the other validation I have implemented works as expected:
{ Page.Title = "Add Game"; //Variables var GameName = Request["Name"]; var Tags = ""; var Gamefile = Request["file"]; //Name validation Validation.Add("Name", Validator.Required("Please give the game a name"), Validator.Regex(@"^[A-Za-z0-9 _]*$", "The name must only contain letters, numbers, space and/or underscores."), Validator.StringLength( maxLength: 100, errorMessage: "Name must be less than 100 characters") ); //SWF file validation Validation.Add("file", Validator.Regex(@"^.*\.(swf|SWF)$", "Invalid filetype, you must upload a .swf flash file") ); if(IsPost && Request.Files[0].ContentLength == 0){ ModelState.AddError("file", "You must choose a file"); } try{ if (IsPost && Validation.IsValid() && ModelState.IsValid) { var db = Database.Open("Surgestuff"); var gCat = ""; var fileData = Request.Files[0]; var fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName); var fileSavePath = Server.MapPath("~/upload/" + fileName); var AddBy = WebSecurity.CurrentUserName; var mod = 0; var count = 0; gCat=Request["formCat"]; Gamefile = fileName; if (Validation.IsValid()){ fileData.SaveAs(fileSavePath); var SQLINSERT = "INSERT INTO Games (Name, file_path, Category, AddBy, Mod, Hits) " + "VALUES (@0, @1, @2, @3, @4, @5)"; db.Execute(SQLINSERT, GameName, Gamefile, gCat, AddBy, mod, count); Response.Redirect("~/Games"); } } } catch(HttpException ex){ ModelState.AddError("file", "File exceeds 10MB"); } }cornball76
Participant
1126 Points
210 Posts
Re: Filetype validation regex not working
Dec 21, 2012 11:36 AM|LINK
Is this all occuring on page load?
If so.
Put the validation creations items inside, so that they don't get recreated each time the page posts back:
If (!Page.IsPostback)
{
}
Also, can whatever button you are clicking handle the upload method?
mhcodner
Member
219 Points
86 Posts
Re: Filetype validation regex not working
Dec 21, 2012 12:01 PM|LINK
If you would like to personally see what I'm talking about I have this live on my subdomain at http://v3.surgestuff.com/Admin/AddGame and it requires you to be logged in so if you're too lazy i created an account with the credentials of Username: test Password: asdf
As a test i uploaded a .swf file, which showed no client side errors and worked as expected. Then i tried uploading a .png, it showed the client side errors but still uploaded and added the info to the database.
Mikesdotnett...
All-Star
154941 Points
19870 Posts
Moderator
MVP
Re: Filetype validation regex not working
Dec 21, 2012 04:28 PM|LINK
The Validation helpers don't work for file uploads. They only work for items that populate the Request.Form collection. File uploads populate the Request.Files collection. So you will have to validate separately:
if(IsPost && Request.Files[0].ContentLength > 0){ if(!Path.GetExtension(Request.Files[0].FileName.ToLower()).Equals(".swf")){ ModelState.AddError("file", "Only Flash files allowed"); } }Beginning ASP.NET Web Pages with WebMatrix | My Site | Twitter
mhcodner
Member
219 Points
86 Posts
Re: Filetype validation regex not working
Dec 22, 2012 01:42 AM|LINK
Ok thank you, I previously tried with:
if (IsPost && Path.GetExtension(Request.Files[0].FileName != ".swf"){ ModelState.AddError("file", "Invalid filetype, you must upload a .swf flash file"); }But that didn't work either. So, I came here for help.
mhcodner
Member
219 Points
86 Posts
Re: Filetype validation regex not working
Dec 22, 2012 09:30 AM|LINK
Is there some way for me to validate the file size that users attempt to upload using server side validation. My try catch doesn't work to catch HttpExceptions so I tried with:
if (IsPost && Request.Files[0].ContentLength >= 10240) { ModelState.AddError("file", "File exceeds 10MB limit"); }But that doesn't seem to be working. What else can I try?
Mikesdotnett...
All-Star
154941 Points
19870 Posts
Moderator
MVP
Re: Filetype validation regex not working
Dec 22, 2012 10:06 AM|LINK
It is the point at which you first try to refence the file that any HttpException due to oversized payloads is thrown, so you should put any attempt to reference the actual file in a try-catch block:
try{ if(IsPost && Request.Files[0].ContentLength > 0){ if(!Path.GetExtension(Request.Files[0].FileName.ToLower()).Equals(".swf")){ ModelState.AddError("file", "Only Flash files allowed"); } } } catch(HttpException ex){ ModelState.AddError("file", "Make sure your file is less than 10MB"); }Beginning ASP.NET Web Pages with WebMatrix | My Site | Twitter
mhcodner
Member
219 Points
86 Posts
Re: Filetype validation regex not working
Dec 22, 2012 10:53 AM|LINK
I have now moved all of my razor code inside the try catch block except it is my validation message that throws me the error: it says the error is the part in my form with
@Html.ValidationMessage("Name")Mikesdotnett...
All-Star
154941 Points
19870 Posts
Moderator
MVP
Re: Filetype validation regex not working
Dec 22, 2012 11:23 AM|LINK
Can you show ALL of the code including the form?
Beginning ASP.NET Web Pages with WebMatrix | My Site | Twitter
mhcodner
Member
219 Points
86 Posts
Re: Filetype validation regex not working
Dec 22, 2012 11:25 AM|LINK
Here is all of the code including the form:
@{ Page.Title = "Add Game"; var GameName = ""; try { //Name validation Validation.Add("Name", Validator.Required("Please give the game a name"), Validator.Regex(@"^[A-Za-z0-9 _]*$", "The name must only contain letters, numbers, space and/or underscores."), Validator.StringLength( maxLength: 100, errorMessage: "Name must be less than 100 characters") ); //SWF file validation if (IsPost && Request.Files[0].ContentLength == 0) { ModelState.AddError("file", "You must choose a file"); } if (IsPost && Request.Files[0].ContentLength > 0) { if (!Path.GetExtension(Request.Files[0].FileName.ToLower()).Equals(".swf")) { ModelState.AddError("file", "Only Flash files allowed"); } } //Variables var Gamefile = Request["file"]; GameName = Request["Name"]; if (IsPost && Validation.IsValid() && ModelState.IsValid) { var db = Database.Open("Surgestuff"); var gCat = ""; var fileData = Request.Files[0]; var fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileData.FileName); var fileSavePath = Server.MapPath("~/upload/" + fileName); var AddBy = WebSecurity.CurrentUserName; var mod = 0; var count = 0; gCat = Request["formCat"]; Gamefile = fileName; if (Validation.IsValid()) { fileData.SaveAs(fileSavePath); var SQLINSERT = "INSERT INTO Games (Name, file_path, Category, AddBy, Mod, Hits) " + "VALUES (@0, @1, @2, @3, @4, @5)"; db.Execute(SQLINSERT, GameName, Gamefile, gCat, AddBy, mod, count); Response.Redirect("~/Games"); } } } catch (HttpException ex) { ModelState.AddError("file", "File exceeds 10MB"); } } <script> function show() { document.getElementById('bar').style.display = 'block'; document.getElementById('form').style.display = 'none'; } </script> <div class="hero-unit"> <h1>Submit a game</h1> <p> Please supply a name for your game and upload the associated flash file and then it will be reviewed by moderators. If successful, your game will appear on the homepage. </p> @Html.ValidationSummary("Submission was unsuccessful, please try again.", excludeFieldErrors: true, htmlAttributes: null) </div> <form id="form" method="post" enctype="multipart/form-data" class="form-horizontal"> <div class="control-group"> <label class="control-label" for="file">Game file.swf (max size of 10MB):</label> <div class="controls"> <input type="file" name="file" data-max-size="10240" title="Game File" @Validation.For("file") required> @Html.ValidationMessage("file") </div> </div> <div class="control-group"> <label class="control-label" for="Name">Game Name:</label> <div class="controls"> <input type="text" name="Name" title="Name" value="@GameName" @Validation.For("Name") required> @Html.ValidationMessage("Name") </div> </div> <div class="control-group"> <label class="control-label" for="Cat">Game category:</label> <div class="controls"> <select id="Cat" name="formCat"> <option selected=@(Request.Form["formCat"] == "Fantasy") value="Fantasy">Fantasy</option> <option selected=@(Request.Form["formCat"] == "Shooter") value="Shooter">Shooter</option> <option selected=@(Request.Form["formCat"] == "Sports") value="Sports">Sports</option> <option selected=@(Request.Form["formCat"] == "Strategy") value="Strategy">Strategy</option> </select> </div> </div> <div class="form-actions"> <button type="submit" onclick="show()" class="btn btn-primary btn-large" data-loading-text="Loading...">Submit Game »</button> </div> </form> <div id="bar" style="display: none" class="progress progress-striped active"> <div class="bar" style="width: 100%"></div> </div>