From d48505cd328d83e39d5706e085ba319715f999a6 Mon Sep 17 00:00:00 2001 From: Nate Abele Date: Wed, 26 Mar 2014 17:56:47 -0400 Subject: [PATCH] feat($urlRouter): force URLs to have valid params --- src/urlMatcherFactory.js | 22 ++++++++++++++++++++++ src/urlRouter.js | 3 +++ test/urlRouterSpec.js | 14 ++++++++++++++ 3 files changed, 39 insertions(+) diff --git a/src/urlMatcherFactory.js b/src/urlMatcherFactory.js index b02622c0b..1870d2341 100644 --- a/src/urlMatcherFactory.js +++ b/src/urlMatcherFactory.js @@ -218,6 +218,28 @@ UrlMatcher.prototype.parameters = function () { return keys(this.params); }; +/** + * @ngdoc function + * @name ui.router.util.type:UrlMatcher#validate + * @methodOf ui.router.util.type:UrlMatcher + * + * @description + * Checks an object hash of parameters to validate their correctness according to the parameter + * types of this `UrlMatcher`. + * + * @param {Object} params The object hash of parameters to validate. + * @returns {Boolean} Returns `true` if `params` validates, otherwise `false`. + */ +UrlMatcher.prototype.validates = function (params) { + var result = true, self = this; + + forEach(params, function(val, key) { + if (!self.params[key]) return; + result = result && self.params[key].is(val); + }); + return result; +} + /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#format diff --git a/src/urlRouter.js b/src/urlRouter.js index 0ad472e6f..d77c96fbd 100644 --- a/src/urlRouter.js +++ b/src/urlRouter.js @@ -292,8 +292,11 @@ function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) { }, href: function(urlMatcher, params, options) { + if (!urlMatcher.validates(params)) return null; + var isHtml5 = $locationProvider.html5Mode(); var url = urlMatcher.format(params); + options = options || {}; if (!isHtml5 && url) { url = "#" + $locationProvider.hashPrefix() + url; diff --git a/test/urlRouterSpec.js b/test/urlRouterSpec.js index 9cd7de370..c296aa75b 100644 --- a/test/urlRouterSpec.js +++ b/test/urlRouterSpec.js @@ -146,6 +146,20 @@ describe("UrlRouter", function () { expect($location.url()).toBe('/old'); })); }); + + describe("URL generation", function() { + it("should return null when UrlMatcher rejects parameters", inject(function($urlRouter, $urlMatcherFactory) { + $urlMatcherFactory.type("custom", { + is: function(val) { + return val === 1138; + } + }); + var matcher = new UrlMatcher("/foo/{param:custom}"); + + expect($urlRouter.href(matcher, { param: 1138 })).toBe('#/foo/1138'); + expect($urlRouter.href(matcher, { param: 5 })).toBeNull(); + })); + }); }); }); \ No newline at end of file