Monday 5 April 2004

File Extension filtering with .NET Regular Expressions

The 3 Leaf: .NET Regular Expression Repository provided a great starting point for writing a file extension filter to prevent certain file-types being uploaded in an ASP.NET HtmlInputFile control, using the RegularExpressionValidator.

Ultimately I came up with this
^([a-zA-Z]\:|\\)\\([^\\]+\\)*[^\/:*?<;>;|]+(\.txt|\.doc|\.xls|\.ppt|\.pdf|\.htm|\.html|\.zip)$
which seems to work OK, HOWEVER it's case-sensitive (so myFile.DoC won't upload).

If you want to only do validation on the server-side, a simple modification will enable 'case-insensitivity'
(?i)^([a-zA-Z]\:|\\)\\([^\\]+\\)*[^\/:*?<;>;|]+(\.txt|\.doc|\.xls|\.ppt|\.pdf|\.htm|\.html|\.zip)$

To really make it nice I wanted client-side validation as well, which meant building a custom validation control inheriting from BaseValidator. Most of the documentation I found was USELESS, but amazingly the 'beta' Longhorn documentation on Client-Side Functionality in a Server Control, Validator Control Samples and Client-Side Functionality in a Server Control
provided all the information I needed on the otherwise cryptic uses of RegisterValidatorCommonScript, RegisterValidatorDeclaration and the other bits and pieces required to implement a client- and server-side validator.

The result, InsensitiveRegularExpressionValidator is still in testing but will be posted soon.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.