Knockout-Contrib / Knockout-Validation

A validation library for Knockout JS
1.02k stars 379 forks source link

Parsing HTML wrong behaviour #651

Open EmilianoBruni opened 7 years ago

EmilianoBruni commented 7 years ago

I saw that all examples attach an "errors" property to an istance of a viewModel but I have a generic class which extends ViewModel

Emi.G.Masters = kb.ViewModel.extend({...

I have a viewModel with two observable. To check parseInputAttributes I set a required attribute in the javascript code and I used the HTML5 attribute "required" for the second one.

this.title = ko.observable('').extend({required: true}); this.description = ko.observable('');

And then, an istance of my class

Emi.G.vm = new Emi.G.Masters;

Now, if I attach errors to the istance

Emi.G.vm.errors = ko.validation.group(Emi.G.vm);

and in the submit I checked errors like this

submit: function(self, e) { if (self.errors().length != 0) { self.errors.showAllMessages(); return; }

all works but if I create a class method

errors: function() { var self = this; return ko.validation.group(self); },

and

submit: function(self, e) { if (self.errors()().length != 0) { self.errors().showAllMessages(); return; }

self.errors()().length is correctly 2 but error messages appears only in the title field, the one extended. And if I filled title with some string, self.errors()().length was 1 but no message appears.

EmilianoBruni commented 7 years ago

The problem is the delayed parsing HTML with kv.util.async.

If I use HTML5 validation attributes the async parsing of HTML5 element is delayed and so here

// if requested insert message element and apply bindings
if (config.insertMessages && kv.utils.isValidatable(observable)) {...

is false and validation message has not been added to HTML.

I solved changing

if (config.parseInputAttributes) {
  kv.utils.async(function () { kv.parseInputValidationAttributes(element, valueAccessor); });
}

with

if (config.parseInputAttributes) {
  kv.parseInputValidationAttributes(element, valueAccessor);
}

Hoping you can solve better this bug.