Email Aaron Blake now at webmaster@aaronblake.co.uk
or contact me

Validate Sitecore Item Programmatically

I was developing an event handler that needed to check if the fields in a Sitecore item were valid before continuing with the event.
I thought Sitecore items might have a property such as:
item.Validation.IsValid

But this isn’t the case. To check if an item is valid, I created a custom function called ValidateItemFields that works in an item event handler.

Solution:

        /// 
        /// Validates all fields in item.
        /// 
        /// 
        /// The item to be validated.
        /// 
        /// 
        /// True if all fields are valid.
        /// 
        private static bool ValidateItemFields(Item item)
        {
            if (((item != null) && !item.Paths.IsMasterPart) && !StandardValuesManager.IsStandardValuesHolder(item))
            {
                item.Fields.ReadAll();
                item.Fields.Sort();
                foreach (Field field in item.Fields)
                {
                    if (!string.IsNullOrEmpty(field.Validation) && !Regex.IsMatch(field.Value, field.Validation, RegexOptions.Singleline))
                    {
                        return false;
                    }
                }

                var formValue = WebUtil.GetFormValue("scValidatorsKey");
                if (!string.IsNullOrEmpty(formValue))
                {
                    var validators = ValidatorManager.GetValidators(ValidatorsMode.ValidatorBar, formValue);
                    var options = new ValidatorOptions(true);
                    ValidatorManager.Validate(validators, options);
                    var valid = ValidatorResult.Valid;
                    foreach (BaseValidator validator in validators)
                    {
                        var result = validator.Result;
                        if (validator.ItemUri != null)
                        {
                            var item1 = Client.ContentDatabase.GetItem(validator.ItemUri.ToDataUri());
                            if (((item1 != null) && StandardValuesManager.IsStandardValuesHolder(item1)) && (result > ValidatorResult.CriticalError))
                            {
                                result = ValidatorResult.CriticalError;
                            }
                        }

                        if (result > valid)
                        {
                            valid = validator.Result;
                        }

                        if (validator.IsEvaluating && (validator.MaxValidatorResult >= ValidatorResult.CriticalError))
                        {
                            return false;
                        }
                    }

                    switch (valid)
                    {
                        case ValidatorResult.CriticalError:
                            return false;

                        case ValidatorResult.FatalError:
                            return false;
                    }
                }
            }

            return true;
        }

Example:

       
/// 
        /// On Item Moving event handler for ImportArticle Items
        /// 
        /// 
        /// The sender object.
        /// 
        /// 
        /// The args.
        /// 0 - Item being moved
        /// 1 - Move destination
        /// 
        public void OnItemMoving(object sender, EventArgs args)
        {
            var item = Event.ExtractParameter(args, 0) as Item;
            if (item == null)
            {
                return;
            }
            
            // Check item type is ImportArticle
            if (!item.Template.Name.Equals(TemplateName))
            {
                return;
            }

            // If ancestor is a child of Content Node, then return
            if (item.Axes.GetAncestors().Any(ancestor => ancestor.Paths.Path.Equals(ContentItemPath)))
            {
                return;
            }

            // If item is valid, return
            if (ValidateItemFields(item))
            {
                return;
            }

            SheerResponse.Alert(ErrorMessage, new string[0]);
            ((SitecoreEventArgs)args).Result.Cancel = true;
        }

2 Trackbacks

  1. […] This post was mentioned on Twitter by Aaron Blake, Aaron Blake. Aaron Blake said: Validate Sitecore Item Programmatically: I was developing an event handler that needed to check if the fields in a… http://bit.ly/c3HoLv […]

  2. By Rules rule | Sitecore and such on 15 April, 2013 at 7:13 pm

    […] tricky than I would’ve liked at first (although it ended up being fairly simple). I came across this blogpost by Aaron […]

Post a Comment

You must be logged in to post a comment.

Email me through this magic form.