AureliaJS

One of the features/plugin that I like best (mainly because its easy to setup and use in its basic form) is the aurelia-validation.

Recently there was some major changes to this plugin, but what I will discuss where is still valid, at least it is for me :).

If you have already Aurelia installed, you only need need to install the plugin, easy way using jspm:

jspm install aurelia-validation

Next we need to load our plugin. On the file that we use for configuring all the plugins (usually main.js on the root of you project):

export function configure(aurelia) {

aurelia.use

.standardConfiguration()

.developmentLogging()



// Validation

.plugin('aurelia-validation'); aurelia.start().then(() => {

aurelia.setRoot('app');

});

}

With this done, we can start to create our form (form.html):

<template>

<form validate.bind="validation" submit.trigger="create()" autocomplete="off">



<div class="form-group">

<label>Name</label>

<input type="text"

id="title"

class="form-control"

placeholder="Title"

value.bind="obj.title" />

</div>



<div class="form-group">

<label>Description</label>

<textarea rows="3"

id="description"

class="form-control"

value.bind="obj.description"></textarea>

</div>



<button type="submit"

class="btn btn-primary btn-sm"

disabled.bind="!validation.result.isValid">Ok</button>



</form>

</template>

And our model (form.js):

import { inject } from 'aurelia-framework';

import { Validation } from 'aurelia-validation'; // inject the validation class that we need

@inject(Validation)

export class Form { constructor(validation) {

this.validation = validation;



this.obj = {

title: '',

description: ''

}; // here we set the rules for our files

this.validation = validation.on(this)

.ensure('obj.title')

.isNotEmpty()

.hasMinLength(2)

.hasMaxLength(120)

.ensure('obj.description')

.isNotEmpty()

.hasMinLength(10)

.hasMaxLength(420);

} // method will be called when form is submitted

create() {



let _this = this;



this.validation.validate()

.then((validatedFields) => {



// IF IT PASSES VALIDATION... YOU CAN DO STUFF

// WHERE WITH UR obj

console.info(_this.obj)

});

}

}

This is how easy is to get some simple validation done. You can go really crazy on the validations that are available. Other methods available range from isEmail(), isBetween(), containsNoSpaces(), containsOnlyAlpha(), isIn(), isGreaterThanOrEqualTo(), and much, much more.

Aurelia used to have a nice page with some examples here, but at the time of this post, probably related to the big changes to aurelia-validation plugin, the page was removed. Hopefully it will return with new updated stuff.

For instant help, you always ask in: https://gitter.im/aurelia/validation