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

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?

Related

How do you insert a newline character within the RegularExpressionValidator ErrorMessage Field?

Consider this code below:
<asp:RegularExpressionValidator
ID="MyTestId"
ValidationGroup="MyTestGroup"
ErrorMessage="You are a silly user. You entered the wrong format for this problem. Please try again. Using this format! ELRLDKX##Z"
ValidationExpression="some unrelated regex"
runat="server"
ControlToValidate="MyTestTextbox">
</asp:RegularExpressionValidator>
Is there a way to insert an escape character of some sort into the ErrorMessage string to ensure that Please try again. Using this format! ELRLDKX##Z is on another line? I have tried, \n with no luck.
The Validator is on a web page, so you can just add html code to the text, like a <br />
ErrorMessage="You are a silly user. You entered the wrong format for this problem.<br />Please try again. Using this format! ELRLDKX##Z"

Expression to catch Single Quote & Special Characters using ValidationExpression in 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"

Multiline textbox new line character regularexpressionvalidator issues

I've been trying to validate a multiline textbox. And of course it doesn't work.
<asp:TextBox ID="t_noteTextBox" runat="server" Width="700" Text='<%# Bind("t_note") %>' TextMode="MultiLine" Rows="3" MaxLength="700" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ErrorMessage="Special Characters not allowed." ForeColor="Red"
ControlToValidate="t_noteTextBox" ValidationExpression="(?m)([a-z]|[A-Z]|[0-9]|[ ]|[-]|[_]|[.]|[,]|[\r]|[\n])*" Display="Dynamic"></asp:RegularExpressionValidator>
<asp:RegularExpressionValidator runat="server" ID="valInput" ControlToValidate="t_noteTextBox" ValidationExpression="^[\s\S]{0,740}$"
ErrorMessage="Please enter a maximum of 740 characters" Display="Dynamic" ForeColor="Red"></asp:RegularExpressionValidator>
The expression works fine as long as I don't add a carriage return. As soon as I go to a new line i get an error.
I even looked up and found the ?m multiline option.
however that doesn't work either.
Testing the regex in Expresso works well.
(?m)([a-z]|[A-Z]|[0-9]|[ ]|[-]|[_]|[.]|[,]|[\r]|[\n])*
But as soon as I put it on the website it doesn't.
Any ideas?
Multiline mode alters the behavior of the anchors (^ or $), which you aren't using.
Singleline mode causes the dot metacharacter to match everything including linefeeds, but you aren't using the dot that way. Like most metacharacters, the dot loses its special meaning inside a character class, so [.] just matches a literal ..
I suspect your problem is that you're allowing the validation to be done on the client side. That is, you haven't set EnableClientScript to "false". Client-side validation uses JavaScript instead of .NET, and the JavaScript regex flavor doesn't support inline modifiers like (?m) and (?s). But that shouldn't matter to you, since you aren't using the dot as a metacharacter.
This should be all you need:
ValidationExpression="[a-zA-Z0-9_.,\s-]*"
You can simplify this quite a bit.
(?m)([\w., -])*
The multiline flag (?m) only allows the anchors ^ and $ to match before and after linebreaks, as opposed to start and end of string normally, so it's not doing what you want here.
If you use \s instead of matching a space, it will match the newline as well.
([\w.,\s-])*

Validation Expression for asp.net

I need to validate textbox value for a password, on client-side.
I want to use RegularExpressionValidator.
Please provide me, the value for 'VALIDATION EXPRESSION'for following two conditions:-
"Password should contain minimum of 8 characters"
"Password should ahve atleast one non -alphanumeric character"
<asp:RegularExpressionValidator
ID="PasswordFormatValidator"
runat="server" Display="Dynamic"
ErrorMessage="Invalid Password Format"
ValidationExpression="??????????????"
ControlToValidate="txtEmail">Invalid Email Format
</asp:RegularExpressionValidator>
Or shall I use Custom Validator. If so, please provide the expression for the req condition.
Here is lots of information about this asp control which demonstrate about the regular expression and how setup ValidationExpression.
Visit MSDN:RegularExpressionValidator Control
for example:
<asp:RegularExpressionValidator id="RegularExpressionValidator1"
ControlToValidate="TextBox1"
ValidationExpression="\d{5}"
Display="Static"
EnableClientScript="false"
ErrorMessage="Zip code must be 5 numeric digits"
runat="server"/>
check this also for more information:
Use Regular Expressions to Constrain Input in ASP.NET
Password
ValidationExpression="(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]"{8,10})$
Validates a strong password. It must be between 8 and 10 characters, contain at least one digit and one alphabetic character, and must not contain special characters.
if you just want to check length must be minimum.(atleast 1) can contain any value. you can replace 1 to check any minimum length of password.
ValidationExpression=".{1,}"

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.

Resources