m-albert
m-albert

Reputation: 1100

Why Doesn't Knockout Validation Required Work Initially?

Check out the following fiddle using knockoutjs and knockout-validation on a simple form. Why doesn't the validation message appear if you click "go" initially?

Javascript:

var viewmodel = function() {
    var self = this;
    self.name = ko.observable(null).extend({
        required: true
    });
    self.validation = ko.validatedObservable({
        name: self.name
    });
    self.go = function() {
        console.log(self.name());
        self.name.isValid();
    };
}
ko.applyBindings(new viewmodel());

HTML:

<input type="text" data-bind="value:name" />
<button type="button" data-bind="click:go">
  go
</button>

Fiddle

Upvotes: 1

Views: 767

Answers (1)

Nick DeFazio
Nick DeFazio

Reputation: 2432

I think the issue here is that there is currently nothing that will trigger the validator to run.

The KO validator plugin by default is triggered on change of a value. On initial load, the value of your input is null, and the click event thats defined wont change this value, forcing the validator to trigger.

Instead, in your go click event, try calling showAllMessages if something is invalid:

var viewmodel = function() {
  var self = this;
  self.name = ko.observable(null).extend({
    required: true
  });
  self.validation = ko.validation.group([self.name]);

  self.go = function() {
    if(self.name.isValid()){
        console.log("I'm valid!");
        console.log("Name: " + self.name());
    }else{
        self.validation.showAllMessages();
    }
  };
}

ko.applyBindings(new viewmodel());

Fiddle

Upvotes: 2

Related Questions