devC
devC

Reputation: 1444

Knockout custom validation issue

Say I have a model with following properties:

function ViewModel() {
     this.SetupTime = ko.observable();
     this.CloseTime = ko.observable();
     this.MinHrs = ko.observable();
}

I need to add a validation rule so that MinHrs > (SetupTime + CloseTime). Whenever one of the three fields is changed this validation should fire. I know I have to write a custom validation for this, for example:

    ko.validation.rules['ValidWorkRange'] = {
    validator: function (val, setuptime, closetime, minhrs) {
        return minhrs > (setuptime+closetime);
    },
    message: '(Shift End - Shift Start) >= Shortest Work Segment'
};

I'm not sure what I have done there is correct, also not sure how to call this validation within the observable.

Can someone please help me out? Thanks in advance

Upvotes: 1

Views: 4013

Answers (2)

Gaurav
Gaurav

Reputation: 8487

Yes you are right, you should create a custom validation to achieve your goal. And you have no need to call validation function, it will be automatically called whenever its associated dependency (observables) will change.

Wroking Fiddle

Note : Please apply the other necessary validation like number etc. Because if you enter text in any input field in the fiddle code than result may be an error.

Here is the custom validation code :

var ValidWorkRange = function(val, param)
{
  if(val && param){
  var minHrs = parseInt(val, 10);
  var setupTime = parseInt(param[0](), 10);
  var closeTime = parseInt(param[1](), 10);
  return minHrs > (setupTime+closeTime);
  }
};

And like this you can apply it on your observable :

function ViewModel() {
     var self = this;

     self.SetupTime = ko.observable();
     self.CloseTime = ko.observable();
     self.MinHrs = ko.observable().extend
     ({
       validation: { 
         validator: ValidWorkRange, 
         message: 'Not valid.', 
         params: [self.SetupTime, self.CloseTime] 
       }
     });
}

Upvotes: 2

Pablo Rodríguez
Pablo Rodríguez

Reputation: 436

I don't know so much about ko validation but probably it can be usefull for you

https://github.com/ericmbarnard/Knockout-Validation

Upvotes: 1

Related Questions