Applying Validation Rules to an Object of a Class


#1

I don’t know how to use Applying Validation Rules to an Object of a Class.
You can see it in below link at section ‘Applying Rules to an Object’.
http://aurelia.io/docs/plugins/validation#defining-rules
As there is no html example .
I tried it myself, but it does not work.

Please see below:


import { ValidationControllerFactory, Validator, ValidationRules, validateTrigger, ValidationController } from ‘aurelia-validation’;
import { autoinject } from “aurelia-framework”;
import { bindable, customElement } from “aurelia-templating”;

@autoinject
export class EditTest {
@bindable properties = { name: “”, id: “”};
@bindable canSave: boolean = false;
private validationController: ValidationController;

constructor(
    private validator: Validator,
    private controllerFactory: ValidationControllerFactory
) {
    this.validationController = controllerFactory.createForCurrentScope(validator);
    this.validationController.validateTrigger = validateTrigger.changeOrBlur;
    this.validationController.subscribe(event => this.validate());
}

attached() {

    ValidationRules.customRule(
        "validName",
        (value) => !/[*<>":?/|\\]/.test(value),
        "Name cannot contain following charactors: \\ / + * & % ?" 
    )


    ValidationRules
        .ensure('name').required()
        .satisfiesRule('validName')
        .on(this.properties);
}

private validate() {
    this.validator.validateObject(this)
        .then(results => {
            return this.canSave = results.every(result => {
                return result.valid;
            });
        });
}

}

And html is here:

template
label>edit model :</label
input value.bind=“properties.name & validate”
button disabled.bind="!canSave">can save</button
template

Anyone can help out? With many thanks.


#2

@Puppy

This is how I do validation change-password-dialog.ts Also take a look at the FormValidator module. I manually trigger the validation. I m not aware of the subscriber on the controller itself. Hope it helps =)


#3

@AlbertoDePena
I’ll take a look how it works.
In my scenario, I need sync validation on input box, not when user click submit button.
Anyway, thank you.


#4

I resolved this issue as I made a mistake. Change like below.

this.validator.validateObject(this) --------> this.validator.validateObject(this.properties )