Brandon Taylor
Brandon Taylor

Reputation: 34553

Resetting aurelia-validation after a successful submit

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.

Upvotes: 2

Views: 1787

Answers (1)

nemesv
nemesv

Reputation: 139758

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' });

Upvotes: 3

Related Questions