Saturday, January 29, 2011

How to Validate FileUpload control to allow only Image Files using RegularExpressionValidator?

To upload images to the server from Asp.Net web application, we will use the FileUpload server control. This control can be validated to upload only Image files using the RegularExpressionValidator control.

To achieve this drag and drop a FileUpload and RegularExpressionValidator control into your aspx page. Then set the ControlToValidate property as “FileUpload1” and the ValidationExpression property as specified below.



ErrorMessage="Invalid Image File"
ValidationExpression=
"^([0-9a-zA-Z_\-~ :\\])+(.jpg|.JPG|.jpeg|.JPEG|.bmp|.BMP|.gif|.GIF|.png|.PNG)$">


So the above RegularExpressionValidator will only allow jpg, jpeg, bmp, gif, png formats image files. You can add more file formats separated by “|” symbol. Also you can specify more special characters after the string “_\-~” to allow the files you want to upload to the server.

No comments:

Post a Comment

Ajax CalendarExtender displaying at wrong position in Chrome

< script type ="text/javascript" language ="javascript">     function onCalendarShown(sender, args)...