I am new to Aurelia. I want to pass validation to my custom element.
The validation does work, but it does not show the validation errors correctly on the screen.
I have 2 problems:
welcome.html
<template>
<require from="./my-element"></require>
<my-element name.bind="myName" val.bind="validation"></my-element>
</template>
welcome.js
import {Validation} from 'aurelia-validation';
export class Welcome {
myName = 'the name';
static inject = [Validation]
constructor(validation) {
this.validation = validation.on(this)
.ensure('name')
.isNotEmpty()
.hasMinLength(3)
.hasMaxLength(10);
}
}
my-element.html
<template>
<form role="form" submit.delegate="save()" validate.bind="val">
<div class="form-group">
<label>name</label>
<input type="text" value.bind="name"><br/>
</div>
<button type="submit">Save</button>
</form>
</template>
my-element.js
import {bindable} from 'aurelia-framework';
export class MyElement{
@bindable name;
@bindable val;
static inject = [Element];
constructor(element){
this.element = element;
}
save(){
this.val.validate()
.then( () => {
alert('correct');
}).catch(error => {
alert('not correct');
});
}
}
Caveats
To get the validation messages we have to trick the validation into thinking the element model is the viewmodel we have set up the validation. This probably shouldn't work, and probably won't work in the future - see http://blog.durandal.io/2016/03/18/preparing-for-infrastructure-update/#validation
First in welcome.js change the ensure('name')
to ensure('myName')
as that is the name of the property you are validating.
import {Validation} from 'aurelia-validation';
export class Welcome {
myName = 'the name';
static inject = [Validation]
constructor(validation) {
this.validation = validation.on(this)
.ensure('myName')
.isNotEmpty()
.hasMinLength(3)
.hasMaxLength(10);
}
}
Second, in welcome.html set the binding from name.bind='myName'
to my-name.two-way='myName'
. This will ensure the view model has been updated with the current value before validating.
<template>
<require from="./my-element"></require>
<my-element my-name.two-way="myName" val.bind="validation"></my-element>
</template>
Third, in my-element.js change your bindable from name
to myName
import {bindable} from 'aurelia-framework';
export class MyElement{
@bindable myName;
@bindable val;
static inject = [Element];
constructor(element){
this.element = element;
}
save(){
this.val.validate()
.then( () => {
alert('correct');
}).catch(error => {
alert('not correct');
});
}
}
And finally update my-element.html accordingly
<template>
<form role="form" submit.delegate="save()" validate.bind="val">
<div class="form-group">
<label>name</label>
<input type="text" value.bind="myName"><br/>
</div>
<button type="submit">Save</button>
</form>
</template>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.