2
votes

I'm leveraging aurelia-validation for my app. What I would like to do is reset the form to empty values after a successful submission.

Here's my view class:

@inject(Validation)
export class Inquire {

    @ensure(isName)
    firstName = '';

    @ensure(isName)
    lastName = '';

    . . .

    constructor(validation) {
        this.validation = validation.on(this);
    };

    sendInquiry() {
        this.validation.validate()
            .then(() => {
                // make API call here, which works
                // reset fields
                this.firstName = '';
                . . .
            }).catch((validationResult) => {
                console.log(validationResult);
            });
    };
};

If I set the firstName, lastName and other fields back to empty strings, the form validation is re-triggered. How can I prevent this from happening?

It seems like you should be able to call .clear() or .destroy() on the ValidationGroup as referenced here in the source code, but that isn't working for me.

1
Calling this.validation.clear() after clearing out the fields is working fine for me... what do you mean on "isn't working for me" ? You see the validation errors or an error in the console? - nemesv
Huh. I can't explain why it works now, but calling .clear() after setting the fields back to their default values is working. Weird! - Brandon
Calling .clear() should be part of the documentation and examples. - Brandon
We always welcome PR's to the docs :) @nemesv can you post that as an answer? - PW Kad
I'll definitely be adding one. I really want to see Aurelia be successful. - Brandon

1 Answers

2
votes

The ValidationGroup's clear() method should do the trick. The point is that you have to call this after you have cleared your fields:

sendInquiry() {
    this.validation.validate()
        .then(() => {

            // make API call here, which works
            // reset fields
            this.firstName = '';
            . . .

            //this resets the validation and clears the error messages
            this.validation.clear();

        }).catch((validationResult) => {
            console.log(validationResult);
        });
};

In newer Aurelia validation versions (after 2016 august) you need to use the reset method:

this.validation.reset()

See in the documentation:

The opposite of the validate method is reset. Calling reset with no arguments will unrender any previously rendered validation results. You can supply a reset instruction to limit the reset to a specific object or property:

controller.reset();
controller.reset({ object: person });
controller.reset({ object: person, propertyName: 'firstName' });