Sitecore CustomValidator does not fire on WFFM cus

2019-05-13 18:04发布

问题:

I've try to extend SingleLineText field on WFFM on Sitecore. This field will have CustomValidator. But ServerValidate event does not fire when page postbacked. The snipped code below.

public class SingleLineText : Sitecore.Form.Web.UI.Controls.SingleLineText
{
   protected override void OnInit(EventArgs e)
   {
       base.OnInit(e);

       var validator = new CustomValidator() { Display = ValidatorDisplay.None };
       validator.ServerValidate += this.Validator_ServerValidate;
       this.generalPanel.Controls.Add(validator);
    }
    protected void Validator_ServerValidate(object source, ServerValidateEventArgs args)
    {
         // does not fire
         var validator = source as IValidator;
         args.IsValid = this.IsValid(validator);
    }
}

The same code works fine on ustom user control field which has ascx.

回答1:

You will want to move your validation code to a new class that implements FormCustomValidator.

public class MySingleLineTextValidator : FormCustomValidator
{ 
    protected override bool EvaluateIsValid()
    {
        if (!String.IsNullOrEmpty(base.ControlToValidate))
        {
            Control controlToValidate = this.FindControl(base.ControlToValidate);
            //Code to validate
        }

        return false;
    }}

Then you will need add a BaseValidator Item in the WFFM Validation Folder, usually this path; /sitecore/system/Modules/Web Forms for Marketers/Settings/Validation. Add the assembly and class to the item.

Now against your custom Field, add the your new BaseValidator item in the Validation field and that's it.

See this post of a wffm custom form validator for a full example