Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aurelia validating nested objects

Tags:

aurelia

I'm trying to validate an object property of an Aurelia ViewModel.

ViewModel

@autoinject
class AddUserForm {
   user: User;
   controller: ValidationController;

    constructor(controllerFactory: ValidationControllerFactory) {
        this.controller = controllerFactory.createForCurrentScope();
    }

    validate() {
        this.controller.validate.then(res => {
            console.log(res.valid);
        })
    }
}

ValidationRules
    .ensure((u: User) => u.id).displayName('User').required()
    .on(AddUserForm)

ViewModel -> View

<template>
    <form click.trigger="validate()">
        <input type="text" value.bind="user.id & validate" />
    </form>
</template>

User

class User {
    id: string
}

The issue I'm having is that the validator is not picking up the nested user object. I'm I missing something to get this working? I read the docs and it seems like this should work. I'm using version ^1.0.0 of the plugin.

like image 503
Rodrigo Avatar asked Sep 11 '25 14:09

Rodrigo


1 Answers

The problem is in your ValidationRules:

ValidationRules
.ensure((u: User) => u.id).displayName('User').required()
.on(AddUserForm)

needs to be

ValidationRules
.ensure((u: User) => u.id).displayName('User').required()
.on(User)

Then to get the controller to run this rule you either need to include "& validate" somewhere in your value.bind for that property, like this:

<input value.bind="user.id & validate" />

or before you call controller.validate(), add the entire object to the controller like this:

this.controller.addObject(this.user);

I use .addObject all the time because it causes validation to run on properties that aren't included in your markup, and I find I prefer that.

like image 195
mgiesa Avatar answered Sep 16 '25 06:09

mgiesa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!