Navigation and service panel


Content

Create Custom Validation Fields in Sitecore WFFM

By Zahid Nawaz on 9. June 2015, 1 Comment

In this post I will let you know how you can create and validate custom fields in Web Form For Marketer.

Web Form For Marketer(WFFM) is one of the key components in Sitecore. It brings a lot of build-in functionality which can be used out of the box. Sometime you need some special kind of features which are not included in WFFM. No problem, you can extend it quite easily.

For one of my customer projects I need to implement a Confirm-Email address feature. Along with the Email Textfield, a Confirm-Email Textfield is also required. The user must not be able to paste anything into the Confirm-Email Textfield.

If you want to achieve this in WFFM, the following steps will guide you through the process.

1. Create a Custom Email Confirmation Field

Following functions need to be implemented for the Confirm-Email Field.

  1. Create a custom Email confirmation field class EmailPasteProtected which inherits from the Email field class provided by Sitecore.
  2. Extend the Email confirmation field by adding a related validation Item ID ( Sitecore Item ID of the Email field) into the public property field RelatedValidationItem .
  3. Add the JavaScript functionality in the OnInit Method, which prevent Pasting into the current field.
  4. Override the OnPreRender function to add the related field Client and Item ID into the Textbox attributes tag. These ids will be used for the Client and Server side validations in later steps.

Here is the code for the EmailPasteProtected class.

    /// <summary>
    /// Add support for Email Paste Protected field.
    /// </summary>
    public class EmailPasteProtected : Email
    {
        /// <summary>
        /// Gets or sets the related validation item.
        /// </summary>
        /// <value>
        /// The related validation item.
        /// </value>
        [VisualProperty("Related Validation Item:", 600), VisualFieldType(typeof(Sitecore.Form.Core.Visual.EditField)), DefaultValue("")]
        public string RelatedValidationItem
        {
            get
            {
                return this.classAtributes["RelatedValidationItem"];
            }
            set
            {
                this.classAtributes["RelatedValidationItem"] = value;
            }
        }

        /// <summary>
        /// Raises the <see cref="E:Init" /> event.
        /// </summary>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            textbox.Attributes.Add("onpaste", "return false");
            base.OnInit(e);
        }

        /// <summary>
        /// Raises the <see cref="E:PreRender" /> event.
        /// </summary>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            Guid relatedItemGuid;
            if (Guid.TryParse(RelatedValidationItem, out relatedItemGuid))
            {
                var id = new ID(relatedItemGuid).ToShortID().ToString();
                var relatedControl = this.FindControl("field_" + id);
                if (relatedControl != null)
                {
                    textbox.Attributes.Add("RelatedValidationItemClientId", relatedControl.ClientID);
                    textbox.Attributes.Add("RelatedValidationItemId", relatedControl.ID);
                }
            }

            if (this.Page != null)
            {
                if (!this.Page.ClientScript.IsClientScriptIncludeRegistered(this.GetType(), "unicValidators"))
                {
                    this.Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "unicValidators", "/scripts/Unic/validators.js");
                }
            }
        }
    }

Add a new field type item under the following path and reference the custom implementation.

    /sitecore/system/Modules/Web Forms for Marketers/Settings/Field Types/Simple Types

1. Create the Server Side Validator for the Confirm-Email field

After creating the Confirm-Email Textfield, you need to create a Server Side validator which will compare the content of the current and related fields. For this purpose create a new class EmailConfimationValidator , which implements the OnServerValidate Method. Within this method you need to find the current(i.e. Confirm Email Paste Protected Textfield) and the related field control (i.e. Email Address Textfield). Once you have the both Textfields, you can validate it by comparing their values.

Here is the code for the Server Side Email Confirmation Validator.

    /// <summary>
    /// Email Confirmation Validator which prove either contents in current field are same as in related field.
    /// </summary>
    public class EmailConfimationValidator : FormCustomValidator
    {
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.WebControls.CustomValidator.ServerValidate" /> event for the <see cref="T:System.Web.UI.WebControls.CustomValidator" /> control.
        /// </summary>
        /// <param name="value">The value to validate.</param>
        /// <returns>
        /// true if the value specified by the <paramref name="value" /> parameter passes validation; otherwise, false.
        /// </returns>
        protected override bool OnServerValidate(string value)
        {
            var controlToValidate = this.FindControl(this.ControlToValidate);
            if (controlToValidate != null)
            {
                var relatedId = ((TextBox)controlToValidate).Attributes["RelatedValidationItemId"];
                if (relatedId != null)
                {
                    var control = this.FindControl(relatedId);
                    if (control != null)
                    {
                        return ((TextBox)control).Text == value;
                    }
                }
            }

            return true;
        }
    }

Now you have implemented an Email confirmation validator, which you need to add as Sitecore item under the following path.

    /sitecore/system/Modules/Web Forms for Marketers/Settings/Validation

I have created a validator named Compare Email - Confirmation and assigned it to the custom code class EmailConfimationValidator . After you have added the new validator in Sitecore, you need to assign it to the previously created E-mail Paste Protected Field.

3. Create a Client Side Validator

After creating the server side validator, we need to create a client side validator as well. A client side validator is just a simple JavaScript method which extract the values of the current (i.e. Confirm Email Paste Protected Textfield) and related (i.e. Email Address Textfield) field control through the Client ID. These values will be validated by comparing them against each other.

Here is the Javascript code for the client side validation.

    function ValidateEmailConfirmation(obj, args)
    {
        var control = document.getElementById(obj.controltovalidate);
        if (control)
        {
            var relatedId = control.getAttribute("RelatedValidationItemClientId");
            var relatedControl = document.getElementById(relatedId);
            if (args && relatedControl && args.Value != relatedControl.value)
            {
                args.IsValid = false;
            }
        }
    }    

You need to add the function name as a parameter in the Compare Email - Confirmation validator item.

<ClientValidationFunction>ValidateEmailConfirmation</ClientValidationFunction>

<ErrorMessage>The {0} and E-mail fields must be the same.</ErrorMessage>

Now you have created a new Text Field along with Client and Server side validation which you can use in WFFM.

Categories  Modules  WFFM Tags -

1 Comment

  1. 20. July 2015 at 12:34

    The code the that you have in 'OnPreRender' should be in 'OnLoad' otherwise you will not get the value in validator's 'OnServerValidate'. Thanks for the post it helped me a lot. Have a nice day and Keep sharing :)

Add your comment

Your email address will not be published. Required fields are marked *

*