Q:

Knockout validation on dynamic viewmodel

I am creating knockout viewmodel dynamically and this code is working fine. I want to add validation in this viewmodel.  Can I add validation in this viewmodel? Is this good approach or should I create viewmodel myself and add validation attributes myself? Or does any client side validation work with data annotations?
var viewModel = function () {
        var self = this;
        self.States  =ko.observableArray();
        self.Countries =ko.observableArray();
        self.showStates = ko.observable(false);
        self.saveData = function (self) { //save data function };
  }
var VM= new viewModel();

$.ajax({
success: function(data)
{ 
   var newVM = ko.mapping.fromJS(data, {}, VM);
   // newVM.FirstName, newVM.LastName
   // I want to add validation in this newVM 
}

A:

Since you are using KO Mapping plug-in to load data, you also have the option to hook into the 'create' event and add validation for individual items if you want. Like in the following: 
$.ajax({
success: function(data)
{ 
  var mappingOption = {    
       'FirstName': {
          create: function (option) {
             return ko.observable(option.data).extend({ required: true });
          }
       }, 
       'LastName': {
          create: function (option) {
             return ko.observable(option.data).extend({ required: true });
          }
       }
   }
   // Now load your viewModel with the mapping option you just specified
   var newVM = ko.utils.arrayMap(data, function (item) {
       return ko.mapping.fromJS(item, mappingOption);
   });
   // ... From now on... in your newVM... firstName and lastName will be 'required'
}

Hope this helps.
Thanks.    

