Skip to content

Commit d48505c

Browse files
committed
feat($urlRouter): force URLs to have valid params
1 parent d8f124c commit d48505c

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

src/urlMatcherFactory.js

+22
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,28 @@ UrlMatcher.prototype.parameters = function () {
218218
return keys(this.params);
219219
};
220220

221+
/**
222+
* @ngdoc function
223+
* @name ui.router.util.type:UrlMatcher#validate
224+
* @methodOf ui.router.util.type:UrlMatcher
225+
*
226+
* @description
227+
* Checks an object hash of parameters to validate their correctness according to the parameter
228+
* types of this `UrlMatcher`.
229+
*
230+
* @param {Object} params The object hash of parameters to validate.
231+
* @returns {Boolean} Returns `true` if `params` validates, otherwise `false`.
232+
*/
233+
UrlMatcher.prototype.validates = function (params) {
234+
var result = true, self = this;
235+
236+
forEach(params, function(val, key) {
237+
if (!self.params[key]) return;
238+
result = result && self.params[key].is(val);
239+
});
240+
return result;
241+
}
242+
221243
/**
222244
* @ngdoc function
223245
* @name ui.router.util.type:UrlMatcher#format

src/urlRouter.js

+3
Original file line numberDiff line numberDiff line change
@@ -292,8 +292,11 @@ function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) {
292292
},
293293

294294
href: function(urlMatcher, params, options) {
295+
if (!urlMatcher.validates(params)) return null;
296+
295297
var isHtml5 = $locationProvider.html5Mode();
296298
var url = urlMatcher.format(params);
299+
options = options || {};
297300

298301
if (!isHtml5 && url) {
299302
url = "#" + $locationProvider.hashPrefix() + url;

test/urlRouterSpec.js

+14
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,20 @@ describe("UrlRouter", function () {
146146
expect($location.url()).toBe('/old');
147147
}));
148148
});
149+
150+
describe("URL generation", function() {
151+
it("should return null when UrlMatcher rejects parameters", inject(function($urlRouter, $urlMatcherFactory) {
152+
$urlMatcherFactory.type("custom", {
153+
is: function(val) {
154+
return val === 1138;
155+
}
156+
});
157+
var matcher = new UrlMatcher("/foo/{param:custom}");
158+
159+
expect($urlRouter.href(matcher, { param: 1138 })).toBe('#/foo/1138');
160+
expect($urlRouter.href(matcher, { param: 5 })).toBeNull();
161+
}));
162+
});
149163
});
150164

151165
});

0 commit comments

Comments
 (0)