Implementing Guid regex in Angular ui-router state: a step-by-step guide

I'm working on a route

.state('mystate', {
    url: '/{id}',
    templateUrl: '/views/partial.html'
});

The id parameter needs to be in the form of a GUID like "2a542f61-5fff-4607-845d-972e6c3ad1e4". How can I include this format in the URL "url: '/{id:?what should i put here}'".

Answer №1

If you want to create a custom parameter type, you can do so by defining it yourself.

var GUID_REGEXP = /^[a-f\d]{8}-([a-f\d]{4}-){3}[a-f\d]{12}$/i;
$urlMatcherFactoryProvider.type('guid', {
  encode: angular.identity,
  decode: angular.identity,
  is: function(item) {
     return GUID_REGEXP.test(item);
  }
});

Check out this demo on Plunker showcasing this solution.

To use this custom type in your URL route expression:

.state('mystate', {
  url: '/{id?guid}',
  templateUrl: '/views/partial.html'
});

For more information, refer to the documentation page.

Answer №2

Check out this live plunker example

If you want to define a URL with regex, you can do so like this:

url: "/{id:(?:[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12})}",

To learn more about url definition options, visit:

http://angular-ui.github.io/ui-router/site/#/api/ui.router.util.type:UrlMatcher

Here's a brief snippet for reference:

'{' name ':' regexp|type '}' - curly placeholder with regexp or type name. If the regexp has curly braces, make sure they are matched or escaped.

Answer №3

After numerous attempts and experimentation, I finally devised the following solution:

$urlMatcherFactoryProvider.type('uuid', {
    encode: angular.identity,
    decode: angular.identity,
    equals: function(x, y) { return x.toUpperCase() === y.toUpperCase(); },
    is: function(value) {
        // Local variable to prevent lastIndex issues
        var UUID_REGEX = /^[a-f\d]{8}-(?:[a-f\d]{4}-){3}[a-f\d]{12}$/i;
        return UUID_REGEX.test(value);
    },
    pattern: /[a-fA-F\d]{8}-(?:[a-fA-F\d]{4}-){3}[a-fA-F\d]{12}/
});

This implementation was inspired by @just-boris's suggestion. One significant modification is the addition of the pattern. Without this, it seems that incorrect UUIDs may not trigger the $urlRouterProvider.otherwise() function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the contrast between img.height and img.style.height?

I'm currently in the process of resizing a series of images by iterating through an array and adjusting their sizes. if(items[0].height > 700 || items[0].width > 700){ items[0].style.height = "700px"; items[0].style.width = "700px"; } As ...

Unable to close Bootstrap modal upon clicking "x" or "close" buttons

Hey everyone, I'm having a bit of trouble with my modal. It appears correctly when clicked to open, and the close buttons seem to detect that my mouse is hovering over them. However, when I click on the buttons, nothing happens and the modal remains o ...

Combine two JSON objects which share a common attribute

I am currently working with two JSON feeds. One feed contains the basic information about a course, while the other contains more administrative details. Here is an example to illustrate what I mean. FIRST {"courses": {"course":{"id":"4","title":"Usi ...

Efficiently Fill JQUERY Mobile Multi-Pages with Dynamic Content

A Question for JQUERY Mobile Beginners: In my basic JQUERY Mobile application, I have a simple setup with two pages. When the user navigates to PAGE2, I need to make an AJAX call to retrieve a JSON object that contains a list of people along with their DB ...

I'm looking for guidance on utilizing the NodeRT (Windows.Gaming.Input) module within an electron environment. Can anyone provide some

I'm having trouble importing the Gamepad class from a specific module, as I keep encountering the error message "Invalid arguments, no suitable constructor found." Here is the code snippet in question: const { Gamepad } = require('@nodert-win10-2 ...

AngularJS Text Size Adjuster

I've managed to change the font and font size separately for different texts, but now I want to apply both functions to one text. How can I achieve this? Below is my HTML code: <div ng-controller="StylesCtrl"> <select ng ...

Simple guide on converting a JavaScript object into JSON

I am currently facing a challenge in converting the following JavaScript object into valid JSON format: [{ '"Sno"': '"1"', '"Purchase Date Time"': '"2017-11-14 14:09:32"', '"Txn Type"': '"COD"&apo ...

Exploring Vue.js integration with Elasticsearch API functions

I have a script written in Vue.js and I am looking to incorporate an Elasticsearch API method. // ./main.js var Vue = require('vue'); Vue.use(require('vue-resource')); import ES from './elasticsearch.js'; new Vue({ el ...

How to Access Qt QWebView Bridge in Webkit IFRAME for Local Page Content

After extensive effort, I successfully implemented the QtWebKit Bridge technique in my Qt C++ (Qt 5.5) application utilizing a QWebView widget. The local Webkit document can now call C++ functions thanks to this bridge. For more information on this techniq ...

Adding a new row to an existing formArray in Angular: A step-by-step guide

Can someone help me figure out how to add a new row and remove a row on this form? editCity() { this.form = this.fo'',))), recepieType: } createForm() { this.form = this.formBuilder.group({ }); } I am looking to implement ...

I would like to modify the text color of a disabled input field

I need to adjust the font color of V1, which is a disabled input field. I want to make it darker specifically for Chrome. Any suggestions on how I can achieve this? https://i.sstatic.net/kioAZ.png Here's my HTML code: <mat-form-field appearance= ...

How can Angular 2 and Firebase be used to search for an email match within all Firebase authentication accounts?

Is there a method to verify the existence of an email within Firebase auth for all registered accounts when users sign up? Can AngularFireAuth be utilized in an Angular 2 service for this purpose? My authentication system is established, but now I am work ...

Modify content once it has been rendered using Jquery

After loading, I want to adjust the style of a specific element. However, I am running into a null pointer issue. function loadFriends() { $("#friendsContainer").load("friends.html"); } selectCurrentSetting(); function selectCurrentSetting() { c ...

Tips for updating an icon in the display by using an if-else statement?

I am utilizing the Ionic Framework along with AngularJS and I am looking to display a specific icon depending on whether a task has been completed or not. Here is my current code snippet: <ion-list> <ion-item ng-repeat="task in tasks" class="i ...

Using Sinonjs fakeserver to handle numerous ajax requests

I utilize QUnit in combination with sinon. Is there a way to make sinon's fakeserver respond to multiple chained ajax calls triggered from the same method? module('demo', { beforeEach: function(){ this.server = sinon.fakeServer. ...

After making changes to the message converters, Jackson and Spring web are encountering issues with deserializing unquoted strings

In my spring controller method, I am accepting a String as the entire RequestBody like this: @RequestMapping(method=RequestMethod.POST) public @ResponseBody DTO method(@PathVariable("userId") long userId, @RequestBody String page) { // Co ...

Displaying a variety of values based on the specific URL

I am attempting to display specific values from an array of objects based on the current URL. For example, if the URL is "localhost/#/scores/javelin," I only want to display the javelin scores from my array. Here is an example of what my array looks like: ...

Sending a variety of data inputs to an API using ajax

I am a beginner in coding and facing some challenges in troubleshooting an issue. My goal is to allow my API to accept multiple data inputs provided by the user through textarea. However, I have encountered a problem where everything works fine when only ...

Exploring query options in jQuery for searching text using the :contains selector

Why is the if statement below not giving me the expected results? Every time it just turns the paragraph yellow, even when the word doesn't match the :contains expression. Here's the query I'm using. $(document).ready(function() { if ($ ...

Creating Structure with Highcharts - Sorting Through Unprocessed Data

In reviewing various demos of highcharts, I noticed that they all tend to adhere to a fairly straightforward data structure: Categories,Apples,Pears,Oranges,Bananas John,8,4,6,5 Jane,3,4,2,3 Joe,86,76,79,77 Janet,3,16,13,15 However, the data I have doesn ...