Tuesday, October 28, 2008

FileUpload file type validation using regular expression validator

The MSDN docs have an excellent example of how to perform file type validation using regular expressions. I tweaked the implementation to allow for configuration via the web.config:

<asp:RegularExpressionValidator
id="vldDocument" runat="server"
ValidationExpression=""
OnLoad="Setup_Doc_Validator"
ControlToValidate="inDocument" />

The codebehind gets the following handler:

    Protected Sub Setup_Doc_Validator(ByVal sender As Object, ByVal e As System.EventArgs)
Dim docValidator As RegularExpressionValidator = CType(sender, RegularExpressionValidator)

docValidator.ValidationExpression = DocumentDAL.GetValidationRegularExpression
docValidator.ErrorMessage = String.Format(ProjectConstants.DOC_TYPE_ERROR_MESSAGE, _
DocumentDAL.GetAllowableTypes())
End Sub
    Public Shared Function GetValidationRegularExpression() As String
Dim allowableTypes As String = DocumentDAL.GetAllowableTypes()
Dim regEx As String = "^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+("

' Note, the file extensions must be PIPE delimited in the Reg Exp, but the web.config uses commas
regEx &= allowableTypes.Replace(",", "|") & ")$"
Return regEx
End Function


No comments: