Expression to catch Single Quote & Special Characters using ValidationExpression in ASP.NET - asp.net

I am working on the asp.net webpage and in the FileUpload control, I am using the ValidationExpression to detect if the selected file has the needed image extension or not. So far it is working fine but I am struggling to detect Single Quote or Special characters in the file name selected by the user with-in the same expression. The idea is to refrain user to use the special characters.
The current code is
<asp:RegularExpressionValidator
runat="server" ID="ImageUpload_TypeValidation"
ControlToValidate="txt_CategoryPicture" Display="Dynamic"
ErrorMessage="Only files with extension JPG/JPEG/GIF/PNG/TIF/BMP are allowed."
SetFocusOnError="true" ValidationGroup="AddNewCategory"
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.png|.PNG|.jpeg|.JPEG|.gif|.GIF|.tif|.TIF|.bmp|.BMP)$">
</asp:RegularExpressionValidator>
Appreciate.

Can you please check and verify this regex.
^.*[\w\s].*[a-zA-Z0-9_#.-]*[\w\s].*(.jpg|.JPG|.png|.PNG|.jpeg|.JPEG|.gif|.GIF|.tif|.TIF|.bmp|.BMP)$

I opted to generate the unique file name for every file upload using Microsoft's inbuilt function of GUID.NewGUID() and converting the image files to .png type. This eliminates any special characters that I didn't want user to have as a filename. Another benefit is that the system will always get the unique file name.
strUploadedFileName = Guid.NewGuid().ToString() & ".png"

Related

RegularExpressionValidator to limit input length and allow empty strings

I'm really bad with regex and was looking at another question almost identical to this but can't get it to work as I need.
I was to use a RegularExpressionValidator that will allow any character up to 255 characters or nothing at all. I tried,
ValidateExpression="^.{255}$"
but it throws an unhanded exception when the textbox that I'm checking is empty.
I've also tried
ValidateExpression="^.{,255}$"
Thank you
Rodney
Did you try ^.{0,255}$? Not sure what exception you are getting though.
EDIT: Also, if struggling with .Net regex, Regex Hero tester is a great help. I know there are other sites, but this one is by far the best, if you ask me.
The proper expression is ^.{0,255}$.
^.{255}$ will only match if there is exactly 255 characters, while ^.{,255}$ will match the literal string "{,255}".
If there are still issues after trying that, can you tell us the exception?
If it throws an HttpRequestValidationException exception, you can use the members of the UnvalidatedRequestValues class.
Mind that "Validation succeeds if the input control is empty" (MSDN). You may add a RequiredFieldValidator field to ensure that the user does not leave a text box blank (if you use the RequiredFieldValidator control inside an UpdatePanel control, make sure that the validator control and the control it is associated with are in the same panel - MSDN):
<asp:textbox id="myTB"
runat="Server">
</asp:textbox>
// ... MAKE SURE YOU DO NOT USE TextMode="Number"!!!
<asp:RequiredFieldValidator
ID="Value1RequiredValidator"
ControlToValidate="myTB"
ErrorMessage="Please enter a number.<br />"
Display="Dynamic"
runat="server"/>
And as for regex, ^.{255}$ means match any character (except newline) exactly 255 times between string start and end. I think it makes sense to allow ^[1-9][0-9]{0,254}$ (for values like '34', '104', etc.).

how to force TextBox to only accept strings

Sorry for the Dummy Question , i know :( ,, but it's only the simple things that dont work with me :((
i have many text boxes and i want the user to only insert String and not Numeric numbers ,
how could i handle it in easy way ??
as it takes every thing and apply it to the database , or should i control it from the Database
PS. i have searched a lot but with no good answer
use [a-zA-Z]+ for ValidationExpression:
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="RegularExpressionValidator"
ValidationExpression="[a-zA-Z]+"></asp:RegularExpressionValidator>
You could take a look at validation techniques for asp : http://msdn.microsoft.com/en-us/library/7kh55542.aspx
This provide a set of tools to check whether the input match what you expect.
You can do it easily in AJAX,just download it from here
first add a script manager to your page then add FilteredTextBoxExtender to the textbox and set it's properties as you wish.
A Regular Expression could be applied to the input
For the basics on RegEx : http://www.regular-expressions.info/tutorial.html
And also see
http://www.regular-expressions.info/dotnet.html
You can use regex to do that with jQuery.
In this example, I replace only digits.
You can adapt the regex to replace any set of characters with an empty string.

how to validate a filename using asp.net regular expression validator

i have the following code to validate my file name entered using regular expression validator
but even after enter correct file name format, its hitting error saying enter valid filename
<asp:TextBox ID="TxtFileName" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="FileNameRegularExpressionValidator" runat="server"
ErrorMessage="Enter valid FileName"
ControlToValidate="TxtFileName"
ValidationExpression="^(\\[a-z_\-\s0-9\.]+)+\.(txt|gif|pdf|doc|docx|xls|xlsx)$">
</asp:RegularExpressionValidator>
At the moment, your regex requires the filename to start with a backslash. Also, your filenames may only contain the lowercase form of letters. Is that intentional?
Also, you're repeating your repeated group, a surefire recipe to bring your server down to its knees with catastrophic backtracking once someone enters an invalid filename that's more than a few characters long.
Perhaps
ValidationExpression="(?i)^[\w\s0-9.-]+\.(txt|gif|pdf|doc|docx|xls|xlsx)$">
would be more suitable?

File Upload Validator always show error message

I add asp.net file upload control as follows:
<asp:FileUpload ID="filesFileUpload" runat="server" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" ErrorMessage="file types not supported"
ValidationExpression="\.(zip|rar|jpg|gif|png|eps|ai|psd|pdf)$" ControlToValidate="filesFileUpload"></asp:RegularExpressionValidator>
And always when I upload file that match the reg expression it show the error. How can I resolve this?
Your regular expression checks for a single dot, followed by one of the extensions, all the way to the end of the string. You need to match the rest of the the filename (.+ matches one or more characters , ^ mean start of string):
ValidationExpression="^.+\.(zip|rar|jpg|gif|png|eps|ai|psd|pdf)$"
See this handy cheat sheet.

Validating an uploaded file's ContentType in ASP.NET

I'm storing some files in my database and since I'm storing them in binary format and not keeping any other information, I have to make sure that all of them are in the same format so that I'll be able to "serve" them later (If there's a simple way to infer the file type from a byte array, please tell, but that's not the focus here).
So, what I need to do is validate every file that is uploaded to make sure it's on the required format.
I've set up a FieldTemplate with a FileUpload control and a CustomValidator:
<asp:FileUpload ID="FileUpload" runat="server" />
<asp:CustomValidator
ID="CustomValidator1"
runat="server"
ErrorMessage="PDF only."
ControlToValidate="FileUpload"
OnServerValidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>
What I'm missing is the code to place in that CustomValidator1_ServerValidate method that checks the uploaded file to make sure it's in the right format (PDF in this case).
Thanks in advance.
Use the FileUpload.PostedFile.ContentType property to validate the MIME type ( should be application/pdf ). For security reasons, also validate that the file extension is appropriate ( .pdf ). You could have a static hashtable containing mappings from MIME type to file extension(s) and use as lookup to validate an extension.
Like ary said. This can all be spoofed. Take a .txt file, rename it to a pdf file and try getting the content type. It will be "application\pdf".
However there is one solution that I have used before. During my brief test with the PDF files, I figured out that the first 3 bytes were always the same. I tried only the first 3 bytes because it seemed enough. The value for the first three bytes is : 37, 80, 68.
So I read the bytes (InputFile1.FileContent.ReadByte()), compared them to the 3 bytes above and if they were the same, then I had a PDF file. Also I read somewhere that you should turn off the script execution for the upload directory in IIS. Hope it helps.
The FileUpload.PostedFile.ContentType was exactly what I was looking for.
Just a heads-up to whoever is trying to do the same thing: it seems that the MIME type for PDF files can be "application/pdf" or "text/pdf", so be sure to check for both.
User can spoof it. In the solution above has no validation of the actual bytes content. I can send you executable and disguise it as pdf and this will not catch it.

Resources