0

My question is in reference to an older question on Stack Overflow:

Knockout validation

The question is regarding date validation in knockout.js and knockout.validation.js.

Does anyone have a good example of knockout binding in MVC 4 that validates a date entry?

Using the above link I implemented the following sample:

ko.validation.rules['simpleDate'] = {
        validator: function (val, validate) {
            return ko.validation.utils.isEmptyVal(val) || moment(val, 'MM/DD/YYYY').isValid();
        },
        message: 'Invalid date'
    };

next, I bound the rules:

self.ChildDateOfBirth = ko.observable().extend({ simpleDate: true });

The whole idea behind this is if the user enters 14/02/2009 then loses focus then a message should popup next to the box as invalid date.

I must be doing something wrong...

Community
  • 1
  • 1
dawriter
  • 425
  • 3
  • 8
  • 21

1 Answers1

3

Did you call ko.validation.registerExtenders(); after you added the validation rule?

According to the documentation you need to call it.

It's working in my jsfiddle.

Wayne Ellery
  • 7,888
  • 1
  • 28
  • 45
  • I did..I was also using MVC 4.0 model..would that be another issue? I noticed that you added the data-binding I'm guessing that is something i need to add? – dawriter Jan 10 '15 at 01:29
  • 1
    Yep. That's how knockout works. You need to bind each field to your client side viewModel. You would normally convert the MVC model to json and assign it to a variable and then pass that into your viewmodel constructor which would then populate your observables. Take a look at one of my [previous answers](http://stackoverflow.com/a/27862522/2326610) that shows how to do it – Wayne Ellery Jan 10 '15 at 01:35
  • I'm going to give this a try - this is most helpful. – dawriter Jan 10 '15 at 02:13