Sunday, April 1, 2018

Sitecore 9 Forms - Server validation - “Email already exists”





Don’t want to save the duplicate data in the form? This is very basic requirement for each type of forms,

Email id should be unique, let’s think the subscription form, where email id is the primary key, we need to validate the unique email id before save the form data. – “email already exists”

In this blog I will explain, how we can place the server-side validation (email already exists) in the new Sitecore 9 forms module.




Let’s start with Sitecore 9 forms, open the form in the Sitecore:

Create the form as per your requirement and drag email field in the form:



Client validation for Email Address

Select the email field > go to the validation section on the right section
Checked the email validator checkbox for checking the valid email id.
We can also change the regular expression of the default Sitecore email validator as below:

Go to /sitecore/system/Settings/Forms/Validations/Email Validator
In parameter field, change the value of regular expression as below:


Add email validator in the forms email field:

Go to email field:
/sitecore/system/Settings/Forms/Field Types/Basic/Email

You can see email validator is selected under allowed validation field as below;






All done for client-side validation, all the above settings are by default provided by Sitecore.

Now, let’s explore the server-side validation,

Server-Side Validation – Email already exists:

Below is the high-level algorithm for server-side validation:



  1. Create the custom validation for forms in Sitecore
  2. Override the validation class and check if email already exists in the database through the code
  3. Assign validation to the email field



Create the custom validation for forms in Sitecore

Go to /sitecore/system/Settings/Forms/Validations
Create the Sitecore item based /sitecore/templates/System/Forms/Validation template

Fill the settings section fields such as type, message, parameters, provide custom class file name with namespace, provide custom error message in message field and parameter if any in parameter field.



Below is the code

using Sitecore.DependencyInjection;
using Sitecore.ExperienceForms.Data;
using Sitecore.ExperienceForms.Mvc.Models.Fields;
using Sitecore.ExperienceForms.Mvc.Models.Validation;
using Sitecore.ExperienceForms.Mvc.Models.Validation.Parameters;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Linq;
using Sitecore.Analytics;
using Sitecore.Diagnostics;
using Sitecore.ExperienceForms.Models;
using Sitecore.ExperienceForms.Processing;
using Sitecore.ExperienceForms.Processing.Actions;
using Sitecore.XConnect;
using Sitecore.XConnect.Client;
using Sitecore.XConnect.Client.Configuration;
using Sitecore.XConnect.Collection.Model;

using Microsoft.Extensions.DependencyInjection;
using Sitecore.ExperienceForms.Data.Entities;

namespace Demo.Feature.Form.Validation
{
    public class EmailExistValidation : ValidationElement<RegularExpressionParameters>
    {

        private IFormDataProvider _dataProvider;


        protected virtual IFormDataProvider FormDataProvider
        {
            get
            {
                IFormDataProvider formDataProvider = this._dataProvider;
                if (formDataProvider == null)
                {
                    IFormDataProvider service = ServiceLocator.ServiceProvider.GetService<IFormDataProvider>();
                    IFormDataProvider formDataProvider1 = service;
                    this._dataProvider = service;
                    formDataProvider = formDataProvider1;
                }
                return formDataProvider;
            }
        }

        public override IEnumerable<ModelClientValidationRule> ClientValidationRules
        {
            get
            {
                if (string.IsNullOrEmpty(this.RegularExpression))
                {
                    yield break;
                }
            }
        }

        protected virtual string RegularExpression
        {
            get;
            set;
        }

        protected virtual string Title
        {
            get;
            set;
        }

        public EmailExistValidation(ValidationDataModel validationItem) : base(validationItem)
        {

        }

        public override void Initialize(object validationModel)
        {
            object regularExpression;
            base.Initialize(validationModel);
            StringInputViewModel stringInputViewModel = validationModel as StringInputViewModel;
            if (stringInputViewModel != null)
            {
                this.Title = stringInputViewModel.Title;
            }
            RegularExpressionParameters parameters = base.Parameters;
            if (parameters != null)
            {
                regularExpression = parameters.RegularExpression;
            }
            else
            {
                regularExpression = null;
            }
            if (regularExpression == null)
            {
                regularExpression = string.Empty;
            }
            this.RegularExpression = (string)regularExpression;
        }

        public override ValidationResult Validate(object value)
        {
            if (value == null || string.IsNullOrEmpty(this.RegularExpression))
            {
                return ValidationResult.Success;
            }
            var formId = Guid.Parse(this.RegularExpression);
            var data = this.FormDataProvider.GetEntries(formId, null, null);
            foreach (var item in data)
            {
                var emailValue = item.Fields.Where(x => x.FieldName == "Emailaddress").FirstOrDefault();
                if (emailValue != null && emailValue.Value.ToLower() == value.ToString().ToLower())
                {
                    return new ValidationResult(this.FormatMessage(new object[] { this.Title }));
                }

            }
            return ValidationResult.Success;
        }
    }
}


Where Sitecore 9 Form data saved?
No more WFFM, all sitecore9 forms data goes to experienceforms database in below 2 tables:


  1. Fielddata
  2. FormEntry




Now, code part is done, its configure this validation on the form, I have created one form called subscriber form for email id as below:





This form contains only one field for email id, and we are checking if email already exists using Sitecore9 forms.

So, when you design your form in the form section in the Sitecore, it will create the items in the content tree under the form folder, next to content editor node, as below:







Here, we need to select the newly created validation called, “email exist validator” in the validations section.

Now all done, let’s check the validation:




I hope this article will help you to configure the custom error message in Sitecore 9 forms.

Happy Sitecoring.


Please connect me if you need any further information on this implementation on Ashish Bansal


Configure Sitecore 9.1 Content Tagging feature with Open Calais

What is Tagging? Tagging refers to the metadata of the content which is assigned to a content by the content creator and the r...