But please don’t go overboard on use of the Event Aggregator! It has its uses, but it is not a message queue, it is one-way only, and I’ve seen it abused far too many times as a communications mechanism between units.

It’s worth noting that function such as required() and maxLength() are simply helpers that point to a predefined satisfies functions, showing that the same features used by rules defined in the library are also available to you in your validation definitions.

So what about when it’s a one-off simple validation rule, not requiring a re-usable generic custom rule? Well there’s even a syntax for that through use of the satisfies() fluent function:

JavaScript

1

2

3

.ensure((m:App)=>m.firstname).displayName("First name")

.required()

.satisfies(v=>v.trim()===v).withMessage('${$displayName} cannot have leading or trailing spaces.')

And to top it all off, both satisfies and custom rules support the return of a Promise for async validation calls, such as making server calls to test username uniqueness, or validating email addresses against existing lists.

Predicates

Sometimes you only want to apply a set of rules if a certain condition has been met in your model. This is referred to as a predicate expression, and one example might be to only validate an email address if the user reports that they want to subscribe to the newsletter:

JavaScript

1

2

3

.ensure((m:App)=>m.email)

.required().when((m:App)=>m.newsletter===true)

.email().when((m:App)=>m.newsletter===true)

This is particularly important when you consider that in this case you may be hiding or excluding the input field if the user is not subscribed to the newsletter, but the validation rule will still be applied because the rule is against the object, not the UI field!
Note that the when condition applies to each rule, and not the overall ‘ensure’ block. This allows finer grain control, albeit it at the expense of slightly more verbose code.

Well the obvious thing is simply style them, but we have some useful additional data available via the controller, such as the control that is linked to the property that was bound to the rule that failed validation…

So we can see from this that the validation controller exposes a Map linking visual elements to validation failures, so we can simply find the first associated element and set focus to that DOM element.
It’s not perfect, as there can be cases where a rule has no visual element, but it will suffice for this demonstration.

So we make sure the template is globally registered:

JavaScript

1

config.globalResources(['./elements/validation-summary.html'])

and we include it at the bottom of our form:

XHTML

1

2

3

4

5

<validation-summary

errors.bind="controller.errors"

controller.bind="controller"

autofocus.bind="true">

</validation-summary>

What do we get? This piece of awesomeness:

You may have noticed this in the middle of the template:<template replaceable part="error">${error.message}</template>

This lets us replace the string with an alternative format in the host view:

Over the last 12 months or so Aurelia has had two different approaches to validation offered as official packages. The first was innovative and reasonably effective, but the code-base was a bit messy, and the original team-member dropped off the map, leaving the team in a tricky situation.

The decision was then made to create a simple interface so that developers could plug in any back-end validation they liked, and an example was created using the Validate.js library. This survived for a few months, but there were many issues related to the underlying engine that made it unsuitable as a solution for the long-term.

Other libraries exist, including Treacherous, which I wrote about here, and this is still available as an option. Now, after many hours of meetings with Jeremy Danyow of the Aurelia core team, we’ve managed to pull in all of the ideas and use-cases learned from these other systems into what we hope is one of the most complete validation solutions out there, let-alone the best for Aurelia.

So let’s take the new version for a spin!

Note that this is example written in Typescript, but if you’re daft enough to sacrifice all that nice type-checking and intellisense and want to use ES6, all you need to do is remove the :type from things (e.g. firstname: string = ''; becomes firstname = '';) and change constructor(private controller: ValidationController) { to say constructor(controller) { this.controller = controller;

The documentation will all be on the Aurelia Hub within the next few hours, but let’s create a really simple example of its use on a form. We’ll start with a simple CLI project, and bodge a simple example into the main form.

First, don’t forget to add aurelia-validation as a plugin in our main.ts, as this is needed even if you’re not using the UI bindings:

JavaScript

1

.plugin('aurelia-validation');

Next, let’s setup the ValidationController and create some rules in our main VM:

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

import{inject,NewInstance}from'aurelia-framework';

import{ValidationRules,ValidationController}from"aurelia-validation";

@inject(NewInstance.of(ValidationController))

exportclassApp{

message='';

firstname:string='';

lastname:string='';

constructor(private controller:ValidationController){

ValidationRules

.ensure((m:App)=>m.lastname).displayName("Surname").required()

.ensure((m:App)=>m.firstname).displayName("First name").required()

.on(this);

}

validateMe(){

this.controller

.validate()

.then(v=>{

if(v.length===0)

this.message="All is good!";

else

this.message="You have errors!";

})

}

}

Now we have to do two things in our view. We have to tell the validator which fields we would like to link to the UI for validation, and we’d like to display the list of validation errors on-screen:

XHTML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<template>

<div>

<p> Firstname: <input value.bind="firstname & validate"/></p>

<p> Lastname: <input value.bind="lastname & validate"/></p>

</div>

<button click.delegate="validateMe()">Validate</button>

<h3>Latest validation result: ${message}</h3>

<ul>

<li repeat.for="error of controller.errors">

${error.message}

</li>

</ul>

</template>

OK, so now we have an extremely unexciting form, but it’s actually pretty powerful. When the form opens the error list is empty, but as we tab over each field the validation engine applies our rules against the associated property (which it found following the Binding), but it only applied the rule when the field lost focus.
It is possible to have the validation fire on every change, on blur, or only manually, and this can be set at a ValidationController level and on a per-field basis.

So we now have everything to test and display errors.

So what if we want to have the errors displayed on a per-field basis?

Well this is highly solution-centric, as the validation system doesn’t know if you want to use Bootstrap 3.0 errors, roll-your-own, or simply change the colour of a field. Even if you simply want to change colour, what class would you like assigning to the input element?

So we now have the option of adding as many validation renders as we like. They take a really simply set of parameters, and you can perform as much DOM manipulation as you like, including making your renders conditional based on information regarding the rule or the associated input element.

Here’s a very simple one to add a class to an element, and to add a DIV element with the message:

(Note that as with many jQuery plugins in JSPM you have to use jspm install npm:jquery-datetimepicker -o "{format: 'global'}")

Adding it to Aurelia proved a little tricky though. First I thought I’d quickly ‘bodge’ it in to check the functionality, so I added some code to the attached() method of my view to call the jquery extension it had added:

XHTML

1

2

3

4

5

6

<input

value.bind="options.deactivateDate"

placeholder="Deactivate at..."

type="datetime"

ref="dt_activate"

/>

JavaScript

1

$(this.dt_activate).datetimepicker();

But things didn’t quite go as expected. While the popup appeared, and the value changed, it wasn’t being bound to the underlying deactivateDate in my object.

Well, it turns out that this is an issue in that jQuery doesn’t always fire change and input events when modifying values in input fields, so the easiest way to solve this is simply to call the event yourself.

So, I might as well bundle this whole thing into a custom attribute, saving the hassle of adding anything in attached() as this will be resolved automatically at the appropriate time:

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

import{inject,customAttribute}from'aurelia-framework';

@customAttribute('datepicker')

@inject(Element)

exportclassDatePicker{

constructor(privateelement){

}

attached(){

($(this.element)asany).datetimepicker()

.on('change',e=>fireEvent(e.target,'input'));

}

detached(){

// remove it in here if possible!

}

}

functionfireEvent(element,name){

varevent=document.createEvent('Event');

event.initEvent(name,true,true);

element.dispatchEvent(event);

}

I save this as datepicker.tsand add it to the list of global resources (so I don’t have to bother using <require> to import it), and my final front-end code looks like this:

XHTML

1

2

3

4

5

6

<input

value.bind="options.deactivateDate"

placeholder="Deactivate at..."

type="datetime"

datepicker

/>

The only other thing to do is to tidy the display up a bit, so it’s not displaying the date and time in full UTC format.

Simply done using a ValueConverter (using moment imported from NPM):

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

import*asmoment from'moment'

exportclassDateFormatValueConverter{

toView(value){

console.warn('to',value);

returnmoment(value).format('YYYY-MM-DD HH:mm');

}

fromView(value){

console.warn('from',value);

returnmoment(value,'YYYY-MM-DD HH:mm');

}

}

Bear in mind that this is being displayed in current time, not UTC, so you may choose to modify the converter to display locally but read and write as UTC to the underlying object.

With the latest updated to typings, this is no longer needed, but at least it helped me and others to get started back in the “good old days” (about 6 weeks ago).

I’ll leave it here though, as it’s got some handy ideas for ways of dealing with NPM and creating your own scripts.

Having spent many days struggling to keep jspm running in my projects, I decided to slide down the razor blade of bleeding edge deployment bundling and transfer our solution from jspm to webpack, given that Rob Eisenberg strongly recommended it.

If you haven’t looked at webpack, check it out here. As a bundling system and dev environment it really is quite awesome. It has a built-in web-server with hot-patching to reflect your code changes immediately, and it’s nicely integrated with npm.

However, as with everything javascript based, I hit a number of speed-bumps. OK, let’s refer to them as ‘speed-mountains’, as with my moderate knowledge of javascript and zero prior webpack experience it turned out that setting up the tooling and ES6 shim stuff was more complex and confusing than expected, but fortunately Dwayne Charrington (@Vheissu in Gitter) kindly tidied up the mess I’d made so far, worked all the fundamentals out for me, then hand-balled it to me to get the last bits working.

One of the main issues we were both experiencing was the apparent lack of recognition by the dev environment that the TypeScript definition files existed, and even when it was told exactly where they were, the system still complained differently depending whether it was webpack or tsc compiling the typescript code!

Now the Aurelia skeleton for ts-webpack used to suggest this method of referring to the definition files; create a _references.ts file, and fill it with the link to every definition required under the npm folder:

This works, but introduces a couple of issues for the typescript compiler tsc. When the compiler runs, it checks the tsconfig.json file, and finds that the node_modules folder is excluded, so it reports many files as missing, although the code still runs. It’s important to remember that typescript definitions don’t affect runtime, only compile time errors an warnings. In addition, the WebStorm IDE inserts red squiggles everywhere, because it too looks at tsconfig and says “nothing of any use exists under node_modules so I’ll never look in there”.

So now we have a couple of references to each definition file, one on the filesGlob section, the other in the files section. Why in both? Well it turns out that tsc and webpack use these files differently. files and filesGlob are documented as being mutually exclusive, so I guess that with no rules for prioritization it’s up to the tool author to choose whichever they prefer.

Plus, on top of all that we still have the issue with IDEs such as WebStorm ignoring the node_modules folder, messing up our code with red squiggles, and refusing to auto-complete or intellisense the code.

So the ideal would be if we had our typings all in one place, but we really don’t want to manually copy/paste them, plus we want to be sure to always have the latest, even when we update our NPM packages or run npm install. Well there is a fairly simple way to do this. By using npm’s script features and a couple of modules, we can create an environment that works in tsc, WebStorm and webpack.

Firstly, install glob-copy and safe-mkdir into your local node so that we have the means to copy our files around and create a destination folder:

Then create a script called ./copytypings.js to generate all of your required definition files to a location under the ./typings/ folder:

JavaScript

1

2

3

4

5

6

7

<span style="color: #999999;">varmk=require('safe-mkdir');

mk.mkdir('./typings/modules');

vargc=require('glob-copy');

gc('./node_modules/aurelia-*/dist/system/*.d.ts','./typings/modules',

function(err,files)

{console.log("copied "+files.length+" files to ./typings/modules");}

);</span>

Next, we’ll add a script to package.json that will re-execute this every time we run npm install:

package.json

JavaScript

1

2

3

<span style="color: #999999;">"scripts":{

"postinstall":"node copytypings.js",

</span>

Now, we want our ./tsconfig.json to include those new files, yet exclude everything in the ./node_modules folder:

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<span style="color: #999999;">{

"compileOnSave":false,

"compilerOptions":{

"target":"es5",

"module":"commonjs",

"emitDecoratorMetadata":true,

"experimentalDecorators":true,

"sourceMap":true

},

"filesGlob":[

"./src/**/*.ts",

"./typings/main.d.ts",

"./typings/modules/*.d.ts",

"!./node_modules",

"!typings/browser.d.ts",

"!typings/browser"

],

"exclude":[

"typings/browser.d.ts",

"typings/browser",

"node_modules"

]

}

</span>

We still include the exclusions in both the exclude section and the filesGlob sections to ensure both tsc and webpack work correctly.

And that’s it! You can test the typescript compilation by typing tsc --noEmit, and the webpack build by typing webpack, and hopefully (apart from a few warnings in Aurelia webpack libraries) you should have an error free compilation for both, and under /typings/ you should also find a modules folder with the aurelia typings.

There are dozens of javascript based spinner libraries available, but given their simplicity I find it easier to create my own.
The key thing is the css that both displays the spinner and blocks the user from clicking other controls on the screen.
This can be divided into two pieces; the blocker:

So how do we use this? We want to be able to enable or disable the spinner from any Promise anywhere in our code, so we’ll simply inject a common busy service with a flag that we can bind our busy functionality to:

JavaScript

1

2

3

4

5

exportclassbusy{

active:number=0;

on(){this.active++;}

off(){this.active--;}

}

and in our base router view we can add the spinner code:

XHTML

1

2

3

4

5

6

7

<template>

<div show.bind="busy.active">

<div class="spinner"></div>

<div class="spinner-blocker"></div>

</div>

<router-view></router-view>

</template>

To use this in a lengthy operation we simply call
busy.on() and
busy.off()

Make sure you always make these calls within a Promise! There’s nothing more frustrating to a user than seeing an error with an infinitely spinning symbol blocking their input!

Here’s an example of displaying a spinner while authenticating a user:

The way Aurelia tracks dependencies on properties is awesome, but there are times when we want to know in code if a property has been updated. Sounds simple, yes? Unfortunately there are a few hurdles.

Firstly, the convention based way of doing this in Aurelia is to create an ‘xxxChanged(newvalue, oldvalue) ‘function on our VM that is auto-magically called whenever property ‘xxx‘ is updated. Unfortunately these changes are restricted to the topmost property, so if we have
currentuser={name:'fred',age:'25'} then we won’t be alerted if the user’s age is changed.
Does this mean that we don’t get binding of the nested element? No, certainly not. Anywhere on the screen where we bind to
${currentuser.age} , the value will be updated correctly, as the act of creating that template binding creates an observer to reflect changes within the bound DOM entity.

Secondly, if we’re observing the three properties of our currentuser (the root and two children) what happens if we replace the object with a new instance, such as
currentuser={name:'Oliver',age:'6'} ? We still have two observers linked to the old object, and these have to removed and disposed of.

Thirdly, we need a way of manually disposing of the observers when we’re finished, or in case we make significant changes to the tree and need to regenerate the observation collection

What we need is a method of observing all of the nested element, and receiving a callback when any of them are modified.

So, with a simple(ish) piece of recursive code we have a means of tracking changes to entities, and having a callback that even supplies the property name that was changed.

The call to observe() returns us a parameterless disposer that we keep track of and can call at any time to dispose of all our observers.

Subclassing is very useful, but how do we link it to our dependency injections?

Aurelia assumes all injection will be against the current object, so we have two options. The first is that if we want to use constructor injection and inject those objects into the base class, we must supply them from the inherited class.

This is fine, as the base class knows nothing of the subclass, but it does mean that when developing the subclass we must replicate the injected object types.

e.g.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

import{Container}from'aurelia-dependency-injection';

import{DialogService}from"aurelia-dialog";

import{DialogController}from"aurelia-dialog";

import{api}from"../services/api";

exportabstractclasspersonBase{

public name:string='Bob';

constructor(public dialogService:DialogService,

public controller:DialogController,

public api:api

)

{

}

Anything deriving from this must perform the dependency injections and call the underlying base class:

The second method is to read the items directly out of the container in our base class, using

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

import{Container}from'aurelia-dependency-injection';

import{DialogService}from"aurelia-dialog";

import{DialogController}from"aurelia-dialog";

import{api}from"../services/api";

constructor()

{

this.dialogService=Container.instance.get(DialogService);

this.controller=Container.instance.get(DialogController);

this.api=Container.instance.get(api);

}

Which you choose to use is largely a matter of preference as behind the scenes Aurelia is using aspects of the second method to implement the first, but there are some fundamental differences that may prevent some plugins working, such as aurelia-dialog. My preference is to use the first method, ensuring current and future compatibility with plugins.

As a final point, it’s worth noting that we can always refer to the base class from our subclass using the ‘super‘ keyword, allowing us to extend the existing page lifecycle:

JavaScript

1

2

3

activate(params){

returnsuper.activate(params);

}

This is one great way to improve code re-use, but beware of growing your base classes, and always consider whether composition might be a better option than inheritance.