Tuesday, December 22, 2015

AngularJS Filter - Format Guid

Working on a project I came to need a formatting filter that would handle presenting GUID in the standard formats. I started by finding a way to validate and harvest the data from the GUID so that I would be able to format it as needed.

I utilized the following method to identify if the string presented would contain a valid GUID. I leveraged Regular Expressions to ensure full validation.

Next I would need to harvest the different portions of the GUID so that I could use them to format it into the requested value.

Now that I have a way of testing and parsing out GUID content I can leverage the final need: Formatting as requested. What are the supported formats? I opened up MSDN and decided if C# supports a format I would want to support that display. Here is the content I found.

MSDN C# Guid ToString()

So now I am ready to handle formatting the Guid in an Angular filter. The following code is my filter and you can see it in action over on my plunkr sample. I have no plans at this time to place this into a bower package, though I have already had requests for this.

Now the first four formats of a GUID are pretty straight forward. But the final hex version is a bit complicated. The code I have may not be the best in performance but it was what I could do to hash it all out. Here is that method.

Finally I just plop down my value in a databind and place the filter into it. By default the filter will use the D format.

There you have it. A filter for presenting a GUID as you most likely will need.

No comments:

Ajax Lesson

NOTE : This lesson uses jQuery as the interface for basic AJAX work. By no means is AJAX a product of jQuery and you do not need jQuery to ...