How to rollback knockout validation errors?

2019-06-05 07:47发布

问题:

I use knockout validation 2.0.3 with entity framework 6.0 and get unexpected validation errors. Here is my workflow:

Step1: (works as expected) Create a new entity with an add-dialog and try to save the new entity. Validation errors are shown because some properties are missing. This is the wanted behavior. The user cancels the dialog and I call unitofwork.rollback() to undo the creation of the new entity.

Step2: Open the edit dialog for an existing entity of the same type. Try to save it as it is. => The validation errors from step 1 are shown again!

How can I clear the validation errors after step1?

If I only execute step2, the save action works just fine.

In a related stackoverflow question It was suggested to use

errors.showAllMessages(false);

That did not resolve my issue.

Related questions:

  • Clear error on Knockout-Validation

  • Clearing or resetting a knockout validation validatedObservable?

  • Knockout Validation - How to show error messages

回答1:

For the validation I used

validation.group(checkedEntity, { deep: true });

The full object tree also considers the entityAspect of the checked entity. The entityAspect is connected to the entity manager. And that entity manager contains the old state of the entity.

The complete cycle is:

fooInstance => entityAspect => entityManager => entityGroupMap => Foo:... => _entities => old entity instance

Therefore I basically have two options:

  • Do not use { deep: true }
  • Make sure that after the rollback the entity manager does not contain the old entity any more:

entityManager.rejectChanges();

entityManager.clear();