Glass field validations in Sitecore views

While using Glass.Mapper with Sitecore MVC, we come across the need very often, to check whether a given field – a link or an image / a video is valid or not.

This would be most necessary in views – where we might not want an empty anchor tag, or a a container html tag to show if the contents were empty. The container tag might have certain CSS associated with it, padding / margins – which might break the design, were the contents empty. We might also have js set to run based on the container tag / classes set on them – which we wouldn’t want running if the contents were empty.

We created extension methods to make repeated checks for validity a little easier.

        public static bool IsValid(this Link link)
        {
            if (link == null || string.IsNullOrWhiteSpace(link.Url) || (link.Type != LinkType.Internal && string.IsNullOrWhiteSpace(link.Text)))
                return false;

            return true;
        }

        public static bool IsValid(this Image image)
        {
            if (image == null || string.IsNullOrWhiteSpace(image.Src))
                return false;

            return true;
        }

        public static bool IsValid(this Video_File video)
        {
            return video != null && video.Video_Url != null && !string.IsNullOrWhiteSpace(video.Video_Url.Url);
        }

While Link and Image – referred above are the standard Glass.Mapper.Sc.Fields classes, Video_File indicated above is actually a template in our site which we use for external videos.

2015-07-05_114306

This enables us to do the following to ensure that there is no scope for null reference exceptions:

2015-07-05_151712

Advertisements

, , , , ,

  1. Override GlassView.RenderLink/BeginRenderLink for internal items | Tech Musingz
  2. Html helpers to render links to items in Sitecore | Tech Musingz

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: