Search code examples
c#asp.netformsvalidationkentico

How can I invalidate or stop processing of the form from inside a submit button click event handler?


I'm trying to implement some custom server-side validation logic for a custom form control running on Kentico v10.0.51 and .NET Framework 4.6. I want this logic to run on submit events, and I want to define the logic in the codebehind of the custom form control. How can I invalidate or stop processing of the form from inside a submit button click event handler? See attached for a reduced test case for example.

https://pastebin.com/Lnt0Rn9y

using System;
using CMS.FormEngine.Web.UI;
using CMS.Helpers;
// ReSharper disable ArrangeAccessorOwnerBody

namespace CMSApp.CMSFormControls.Custom
{
    public partial class ServerSideValidator : FormEngineUserControl
    {
        public override object Value
        {
            get { return txtValue.Value; }
            set { txtValue.Value = ValidationHelper.GetString(value, string.Empty); }
        }

        protected override void OnInit(EventArgs e)
        {
            Form.SubmitButton.Click += SubmitButtonOnClick;
            base.OnInit(e);
        }

        private void SubmitButtonOnClick(object sender, EventArgs e)
        {
            var valid = CustomValidationHelper.ServerSideValidationMethod(Value);

            if (!valid)
            {
                //TODO: Invalidate the form before save or notify. (Form.?)
            }
        }
    }
}

Solution

  • Use the overrideed method:

    /// <summary>
    /// Returns true if a color is selected. Otherwise, it returns false and displays an error message.
    /// </summary>
    public override bool IsValid()
    {
         if ((string)Value != "")
         {
             return true;
         }
         else
         {
             // Sets the form control validation error message
             this.ValidationError = "Please choose a color.";
             return false;
         }
    }
    

    Inside the else statement perform your validation on the field or expressions you want to validate and return a message based on what you're validating.