concept validation controller in category aurelia

appears as: validation controller, Validation controllers, The validation controller
Aurelia in Action

This is an excerpt from Manning's book Aurelia in Action.

Each view-model that requires validation has one or more mapped validation controllers. Validation controllers are orchestrators that are responsible for receiving validation triggers (such as an input change or blur event) and responding to these triggers by applying the relevant validation feedback to the view via a validation renderer.

Listing 7.15. Adding a validation controller to EditBook (edit-book.js)
import {bindable, inject, computedFrom, NewInstance} from 'aurelia-
     framework';                                                       #1
import {EventAggregator} from 'aurelia-event-aggregator';
import {BootstrapFormRenderer}
       from '../../renderers/bootstrap-form-renderer';                 #2
import {ValidationRules, ValidationController}
       from 'aurelia-validation';                                      #3
import _ from 'lodash';

@inject(EventAggregator,
        NewInstance.of(ValidationController) )                         #4
export class EditBook{

    @bindable editMode;
    @bindable book;
    @bindable selectedGenre;
    temporaryBook = new Book();                                        #5

    constructor(eventAggregator, bookApi, validationController ){      #6
        this.validationController = validationController ;             #7
        this.controller.addRenderer(new BootstrapFormRenderer());      #8
        ...
    }

    ...

   @computedFrom('temporaryBook.title',
                  'temporaryBook.description',
                  'temporaryBook.rating',
                  'temporaryBook.ownACopy',
                  'temporaryBook.genre',
                  'saved',
                  'temporaryBook.shelves',
                  'temporaryBook.timesRead')                           #9
    get canSave(){
        if(!this.temporaryBook.Id) return false;

        return this.isDirty();
    }

    ...

    save(){
        this.controller.validate()                                     #10
                        .then(result => {                              #11
                            if (result.valid) {                        #12
                                this.loading = true;
                                this.publishBookSavedEvent();
                            }
                        });
    }    ...
}
export class Book {                                                    #13
  title='';
  description='';
}

Now that the validation controller, validation rules, and renderer are in place, it’s time to make use of the validation setup from the edit-book.html view file.