How to set validation to Arrays using knockout validation?
My object definition
//c# code
public class Trophy
{
public string Name { get; set; }
public string Category { get; set; }
public double PrizeMoney { get; set; }
}
public class Player
{
public string Name { get; set; }
public List<Trophy> Trophies { get; set; }
}
I am able to set validation like 'required' using ko validation for simple types like 'Name' but I cannot set to Trophies which is an array. For simple types I use as below
// javascript code
var localModel = ko.mapping.fromJSON(getPlayerModelJson());
// Validation
localModel.Name.extend({ required: { message: 'Please enter first name' } });
Please let me know how to do for Name, Category and PrizeMoney with in Trophies?
I tried to make use of 'Customizing object construction using “create”' as mentioned in the
http://knockoutjs.com/documentation/plugins-mapping.html but it is creating a duplicate Trophies array item, for example if I have two list item in the Trophies the resulting object also has two items but it is duplicate of last item
// Java script code
var Trophies = function (data) {
Name = ko.observable(data.Name).extend({ required: { message: 'Please enter name' } }),
Category = ko.observable(data.Category),
PrizeMoney = ko.observable(data.PrizeMoney)
}
var localModel = ko.mapping.fromJSON(getPlayerModelJson(), TrophiesMapping);
//Custom mapping
var TrophiesMapping = {
'Trophies': {
create: function (options) {
return new Trophies(options.data);
}
}
}
All I wanted is validate the properties with in the array. Thanks