Monday, February 7, 2011

CustomValidator - returns false but form submits anyway

I think this has bitten me a couple of times now.  If you implement a CustomValidator with server side validation in ASP.Net, then you set args.IsValid to true if the validation passes or to false if the validation fails.  But even if you return false, the form continues the submit process anyway!

The trick is that when you set args.IsValid, that sets a flag in the Page class called Page.IsValid, and you still need to check that Page.IsValid flag somewhere in your form processing.  For example, I check it in my button click handler and just return from the method if Page.IsValid is false.  The error message that you set for your CustomValidator will then be displayed.

I should mention that the post that got me part of the way to figuring this out was on Egghead Cafe, but it lacked example code and the actual property name.  Here is some example code of using this process to limit the file size on an asp:FileUpload control using a CustomValidator with server side validation.

.aspx file
...

<asp:FileUpload runat="server" ID="uplResume" />
<asp:CustomValidator ID="FileSizeValidator" runat="server" ControlToValidate="uplResume"
ErrorMessage="File size should not be greater than 2 MB." OnServerValidate="FileSizeValidator_ServerValidate"></asp:CustomValidator>
...

.aspx.cs file
...

    protected void FileSizeValidator_ServerValidate(object source, ServerValidateEventArgs args)
    {
        int fileSize = uplResume.FileBytes.Length;
        if (uplResume.FileBytes.Length > 2 * MEGABYTES)
        {
            args.IsValid = false;
        }
        else
        {
            args.IsValid = true;
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
        {
            return;
        }
        // do processing for valid form here
    }