Field Validation on Specific Template Types


Recently I asked to add validation on specific field.  That is out of the box provided by Sitecore you need to go to field item and then select the validation items in the Validation Rule Section. But here is the point I am using same field in many different template types.

So I created a separate data template for specific field type (For example Title) and inherited this field template into many data templates and I was asked to add validation on the field but on some data templates not all of them.

So if I am adding validation rules to field then it will get added to all the data template where it inherited. And this is we don’t need to do. So here I started thinking that how can implement this as per data template specific.

I finally decided to create custom validation rule this was the only way I found to handle the same.

  1. Created a Folder with name of my site under /sitecore/system/Settings/Validation Rules/Field Rules location. I did it to make my rule separate.
  2. Created Validation Rule item by /sitecore/templates/System/Validation/Validation Rule template. (For example I am creating Required field validation).
  3.  Add the basic field value like Title, Description etc.
  4. In this step we need to add value in Type and Parameter but those are depend on the class which we need to create for this.

Below is the class which created for this –

/// <summary>
    /// Class CustomRequiredFieldValidator.
    /// Implements the 
    /// </summary>
    /// 
    [Serializable]
    public class CustomRequiredFieldValidator : StandardValidator
    {
        /// <summary>
        /// Initializes a new instance of the  class.
        /// </summary>
        public CustomRequiredFieldValidator()
        {
        }

        /// <summary>
        /// Initializes a new instance of the  class.
        /// </summary>
        /// The Serialization info.
        /// The context.
        public CustomRequiredFieldValidator(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }

        /// <summary>
        /// Gets the name.
        /// </summary>
        /// The validator name.
        public override string Name
        {
            get
            {
                return "Required";
            }
        }

        /// <summary>
        /// When overridden in a derived class, this method contains the code to determine whether the value in the input control is valid.
        /// </summary>
        /// The result of the evaluation.
        protected override ValidatorResult Evaluate()
        {
            var templateID = MainUtil.GetStringList(true, this.Parameters["templateids"].Split('|'));
            if (templateID.Contains(this.GetItem().TemplateID.ToString()))
            {
                if (!string.IsNullOrEmpty(this.ControlValidationValue))
                {
                    return ValidatorResult.Valid;
                }

                this.Text = this.GetText("Field \"{0}\" must contain a value.", this.GetFieldDisplayName());
                return this.GetFailedResult(ValidatorResult.CriticalError);
            }

            return ValidatorResult.Valid;
        }

        /// <summary>
        /// Gets the max validator result.
        /// </summary>
        /// The max validator result.
        /// This is used when saving and the validator uses a thread. If the Max Validator Result
        /// is Error or below, the validator does not have to be evaluated before saving.
        /// If the Max Validator Result is CriticalError or FatalError, the validator must have
        /// been evaluated before saving.
        protected override ValidatorResult GetMaxValidatorResult()
        {
            return this.GetFailedResult(ValidatorResult.Error);
        }

 

So in this class we are just checking the condition for required value.

Now lets switch to steps above specially moving back to Step 4 our last step –

So we need to add assembly reference in type field as below –

dm1

And in Parameter field we need to provide pipe separated template id’s where we need to apply the validation.

So here the template id’s are the one where we wan’t to specially add the validations.

 

Now the final steps we need to add this custom validation to the field item.

Navigate to your field item and add the validation in Validation rules section as below – I added it in all four fields but it’s on you what is your requirement – Quick Action Bar, Validate Button, Validator Bar and Workflow. –

dm_2.png

 

This was the interesting implementation I did there are may be many more ways but I found this easy for me.

Stay connected for my next post for adding custom validation for max length 700/300 char again template specific.

 

 

This entry was posted in Sitecore, Sitecore Validation Rules, Uncategorized and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s