Knockout-Validation
Knockout-Validation copied to clipboard
Why does clearError() mark model as valid?
ko.validation.init();
var myValue = ko.observable().extend({ required: true, minLength: 3 });
console.log(myValue.isValid()); // false
myValue.clearError();
console.log(myValue.isValid()); // true - I believe this is wrong
Use case: I have a form in a dialog, with a required field and some other rule. messagesOnModified = true On fresh start, when submitted empty, KO Validation treats the model as invalid, all is good.
User types in an invalid value, error shows up. He clicks cancel and the form is hidden. I clear the value and errors with myVal(null) and myVal.isModified(false).clearError().
He opens the form again and submits it right away empty. KO Validation will wrongly report the model as valid. The reason behind this wrong behaviour is that the previous call to clearError() not only removed the error message, but also marked the field as valid which wasn't true.
I know I can work around this by using myVal.error(null) instead of clearError().
@xpavp03 Since you're using messagesOnModified = true, the best approach would be to just set isModified(false) once you close the modal. That way your fields keep the current validation state - just the error messages would go away.
I wouldn't say the behaviour is incorrect since those methods provide a way to manually change the validation state.
I will leave this issue open for a while to let other people leave a feedback on this.
Oh right! I didn't realize isModified(false) would be enough.
I found it weird that a method that by its name clears errors, would also do something more. So I thought I'd bring this up. Thank you for your comment.
@xpavp03 you can use input.error(null) to hide error message.But i agree, method behavior is strange.
In my mind clearError should do this:
input.isModified(false);
input.error(null);
Or something similar.