3

I am using fileupload control to upload file and at same time using regular expression for validating file name.

I want following file extension to be uploaded for .doc, .docx, .pdf i use following command to valid file name

ValidationExpression="[a-zA-Z\\].*(.doc|.DOC|.docx|.DOCX|.pdf|.PDF)$"

 <asp:FileUpload ID="FileUpload1" runat="server" CssClass="fileUpload" />
<asp:RequiredFieldValidator ID="ValidateF1" runat="server"  ErrorMessage="*" CssClass="row-validate"  ControlToValidate="FileUpload1"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="ValidateEx" runat="server"   ValidationExpression="[a-zA-Z\\].*(.doc|.DOC|.docx|.DOCX|.pdf|.PDF)$" ControlToValidate="FileUpload1" ValidationGroup="Careers" ErrorMessage="*"></asp:RegularExpressionValidator>

It fails to validate following file name

(K)+J01461+abced+high+En+(HR)(1).pdf I am not sure why it fails while it works for ABC_COMPANY_Privacy_v4.0_123456(5).pdf

Am i using the wrong validation expression. I want to allow any file name with extension as mentioned above.

2 Answers 2

7

try this

ValidationExpression="^.*\.(doc|DOC|docx|DOCX|pdf|PDF)$"
Sign up to request clarification or add additional context in comments.

1 Comment

If i only need to check for file extension then can i use @"\.(pdf|doc|docx)$" will it validate even file name which has multiple dots . for example file.name.pdf or file.name+abcd(1).docx or with spaces also
2

It depends on entirely on what you consider a valid file name. Your current expression only captures file names with alphanumeric characters and the character \\.

From your two examples, it looks like you want to include ()+_, as well as multiple dots, so you can fix your expression by just adding those into the character class.

ValidationExpression="[_.a-zA-Z()+\\]*\.(doc|DOC|docx|DOCX|pdf|PDF)$"

If you want to include the space character as well, then just stick that in there too.

ValidationExpression="[_.a-zA-Z()+\\ ]*\.*(doc|DOC|docx|DOCX|pdf|PDF)$"

If you want to permit all possible characters before the extension, then using Vignesh's solution will certainly do it for you.

2 Comments

If i only need to check for file extension then can i use @"\.(pdf|doc|docx)$" will it validate even file name which has multiple dots . for example file.name.pdf or file.name+abcd(1).docx or with spaces also
@KnowledgeSeeker, It depends on whether the Match function you are using is trying to match the entire string or only part of the string. If you try it and it works on one case, it should work in the general case also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.