Where to validate query params


#1

Where is the appropriate place to validate query params? I basically want to check if a query param is valid, and if not, set it to a default value. I had assumed it would be in the Controller’s init(), but when I look up my params there, all I get is the default values I had set. Is there another lifecycle hook I could use in the Controller, or am I supposed to do it in the accompanying route?


#2

model is a good place. The query param is deserialized, you can get it from the params argument. If any query params is not valid, abort the transition and transition (or replace) to the route itself with new query params.


#3

Thanks for the suggestion. I wasn’t sure if model() was an appropriate place to do my param checking. Before you answered, I was doing some searching, and it seemed like beforeModel(transition) would be another good place to do validation, so that’s where I ended up doing my param checking and transitioning, if required.

I did run into an issue, however, where I’d receive "TypeError: Cannot read property 'name' of undefined" upon using this.transitionTo(), even though the transitions succeeded. I believe it’s similar to the issues described here:

https://github.com/emberjs/ember.js/issues/12169#issuecomment-147632472

I ended up using a workaround described within the comments.


#4

There are 2 ways I can think of on validating query params. One is in the model hook, as @lightblade suggested and another one is in the setupController hook since the query params are properties on the controller. Here are the 2 examples in action

Validation in the model hook

Validation in the setupController hook