1
votes

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

2

2 Answers

0
votes

Here's a JSFiddle using mapping. I think your problem might be the following line:

var localModel = ko.mapping.fromJSON(getPlayerModelJson(), TrophiesMapping);

I copied your code and was scratching my head as to why it didn't work until I changed it to

ko.mapping.fromJS(...)
-1
votes

Take a look at this example upida.azurewebsites.net

Click - Add Order, and in the new Window you will see Array of products. Try to add several products, and fill them with data. Try to Save, and see how validation works, it is knockout.js.

It is server side validation, with no any client side constraints.