Kentico: Custom BizForm Validation

7 September 2011

Here's a quick tip on how to add custom validation to your BizForms in Kentico - for example, ensuring that a user has checked a "terms and conditions" checkbox, or that email addresses match. The BizForm control in Kentico provides quite a few events for which you can hook into, such as OnOnSaveFailed, OnOnValidationFailed, etc - but the one we're interested in is OnOnAfterValidate - this occurs after Kentico runs the built in validation for BizForms, but before it saves a new row to the database. (Note: if you try to write validation code for OnOnBeforeValidate, you'll quickly notice that the Validation Error form labels won't display on the bizform no matter what you do, so stick to OnOnAfterValidate.)

So the basic premise is to write a method to grab the fieldcontrols of the bizform (which you can usually access through myBizform.BasicForm.FieldControls[fieldName].Value, although they're not always FormEngineUserControl objects), check what you need to check and if an error has occured, get the error label through BasicForm.FieldErrorLabels[fieldName], set an error message on it and make it visible, then set BizForm.StopProcessing = true.

It's a lot easier to see in code. The aspx:

<cms:BizForm ID="myBizForm" runat="server" FormName="TestBizForm" OnOnAfterValidate="CustomValidation"/>

And the codebehind:

protected void CustomValidation()
        BasicForm mainForm = myBizForm.BasicForm;

        //check emails match
        FormEngineUserControl emailField = (FormEngineUserControl)mainForm.FieldControls["Email"];
        FormEngineUserControl confirmEmailField = (FormEngineUserControl)mainForm.FieldControls["ConfirmEmail"];
        if (!emailField.Value.ToString().Trim().Equals(confirmEmailField.Value.ToString().Trim()))
            RaiseError("Email", "The confirmation email address does not match the provided email address.", myBizForm);

        //check terms of use accepted
        if (!((CheckBox)mainForm.FieldControls["AcceptTermsOfUse"]).Checked)
            RaiseError("AcceptTermsOfUse", "You must accept the Terms of Use to continue.", myBizForm);

    private void RaiseError(string sFieldControl, string sErrorMessage, BizForm form)
        LocalizedLabel errorLabel = (LocalizedLabel)form.BasicForm.FieldErrorLabels[sFieldControl];
        errorLabel.Text = sErrorMessage;
        errorLabel.Visible = true;
        form.StopProcessing = true;

        // Display error message
        Label mainErrorLabel = ((Label)(form.FindControl("lblErrorLabel")));
        if (mainErrorLabel != null)
            mainErrorLabel.Text = "The entered values cannot be saved. Please see the fields below for details.";       //note that you need to set this label manually when doing custom validation, which appears at the start of the form.
            mainErrorLabel.Visible = true;

Pretty easy, right?

Tags: validation, BizForm, Kentico

Add a Comment

No Comments