Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout validation doesn't add hasError class if exclude validationElement binding

I have added knockout validation to my model.

This works fine:

//init validation
ko.validation.init({
    registerExtenders: true,
    insertMessages: false,
    messagesOnModified: false,
    decorateElement: true,
    errorElementClass: 'hasError'
});

// has required validation for model observable
self.CompanyName= ko.observable(data ? ko.unwrap(data.CompanyName) : '').extend({ required: true });

HTML

//binding
<span class="inline-edit-view" data-bind="text: CompanyName, validationElement: CompanyName"></span>

This adds hasError to the invalid element. If I remove validationElement, though, it doesn't work.

Question is: Why should I use validationElement? It seems counter-intuitive to me.
I already have extend {required: written} for each element and I do not want to write a validationElement binding for each observable.

like image 961
renathy Avatar asked May 07 '26 04:05

renathy


1 Answers

You need to use the validationElement binding because you are using the text binding.

The Knockout.Validation plugins overrides the value and the checked bindings to apply the different validation aspects like the errorElementClass so if you are using one of this two bindings then you don't need to explicitly use the validationElement binding.

However if you are using different bindings like text then you are responsible to mark your HTML with the validationElement and the validationMessage bindings if you want the validation plugin to use your classes or insert error messages etc.

like image 105
nemesv Avatar answered May 09 '26 18:05

nemesv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!