Skip to content

Commit

Permalink
feat($urlRouter): force URLs to have valid params
Browse files Browse the repository at this point in the history
  • Loading branch information
nateabele committed Apr 11, 2014
1 parent d8f124c commit d48505c
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/urlMatcherFactory.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions src/urlRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
14 changes: 14 additions & 0 deletions test/urlRouterSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}));
});
});

});

0 comments on commit d48505c

Please sign in to comment.