clearError() in KO Validation updates validity too

Let me start with the take-away message:

Don’t clear errors with clearError() if you reuse your form and if you set messagesOnModified to true (default value).

Now why. Say you have a Create Thingy form with a field for the new thingy name. Name is obligatory but you don’t want the creating experience to start with an error message. So you keep messagesOnModified at true.

User opens the dialog, chooses a name that is invalid and then gives up – clicks Cancel. Then following a sudden outburst of creativity, he opens the dialog again. At this point, you want the old invalid attempt to be gone, all errors cleared.

My solution was to clear the form values on, reset isModified(false) and get rid of errors with clearErrors(). Well, it turned out that if the user submitted the form immediately, with an empty value, it passed as valid!

The culprit was clearErrors() – it not only removes the error message but also marks the model as valid! So the right procedure here is to use error(null) instead of clearErrors().

Tags: ,

Leave a Reply