Jon's Blog

.NET Development & More

File Upload: File Extension Validation

This is an easy way to validate the file extension on a FileUpload control.  This way you won't have to postback to the server to validate.  Unless, of course, the user has JavaScript turned off.  The example below is for images (JPEG, GIF, or PNG).

<asp:RegularExpressionValidator ID="regxImage" runat="server" Text="*" 
ErrorMessage
="Image must be a JPEG, GIF, or PNG."
ValidationExpression="(.*?)\.(jpg|JPG|jpeg|JPEG|jpe|JPE|png|PNG|gif|GIF)$"
ControlToValidate="myFileUpload" />

ASP.NET: Add New Error Message to Validation Summary Control

You can use this method to add a new error to an existing validation summary control from your code-behind page.  Don't forget to use the proper ValidationGroup that your validation summary is using.

protected void AddErrorToValidationSummary(string errorMessage)
{
CustomValidator custVal = new CustomValidator();
custVal.IsValid = false;
custVal.ErrorMessage = errorMessage;
custVal.EnableClientScript = false;
custVal.Display = ValidatorDisplay.None;
custVal.ValidationGroup = "MyValidationGroup";
this.Page.Form.Controls.Add(custVal);
}