Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / regular-expression

Regular Expression to Validate File Path and Extension

4.95/5 (10 votes)
28 May 2012CPOL 275.8K  
Regular Expression to validate the file path and extension and it is compatible with JavaScript and ASP.NET

Introduction

Recently, I was looking for a regular expression to validate a file path and extension. I found several of them on Google, but none of them fit my requirement. So I decided to put together a version that suits my need. Here is the Regular Expression to validate the file path and extension and it is compatible with JavaScript and ASP.NET. I hope someone will find this information useful and that it will make your programming job easier.

^(?:[\w]\:|\\)(\\[a-z_\-\s0-9\.]+)+\.(txt|gif|pdf|doc|docx|xls|xlsx)$

Explanation

^(?:[\w]\:|\\) -- Begin with x:\ or \\
 
[a-z_\-\s0-9\.] -- valid characters are a-z| 0-9|-|.|_ (you can add more)
 
(txt|gif|pdf|doc|docx|xls|xlsx) -- Valid extension (you can add more)

Matches

\\192.168.0.1\folder\file.pdf
\\192.168.0.1\my folder\folder.2\file.gif
c:\my folder\abc abc.docx
c:\my-folder\another_folder\abc.v2.docx

Non-Matches

\\192.168.0.1\folder\fi<le.pdf
\\192.168.0.1\folder\\file.pdf
\\192.168.0.1\my folder\folder.2\.gif
c:\my folder\another_folder\.docx
c:\my folder\\another_folder\abc.docx
c:\my folder\another_folder\ab*c.v2.docx
c:\my?folder\another_folder\abc.v2.docx
file.xls

Test It

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)