Reputation: 6045
I have a scenario when i dynamically add multiple rows using template
way i need to write down a validation if CountryCode
(which should be unique) having same value in two or more dynamically generated rows .
working fiddle : http://jsfiddle.net/JL26Z/73/
Well i am thinking can this be possible using custom validation code but i am not sure how to proceed i mean how to compare in validator
function inside validation
.
And the same can be done on click of submit
in save function like we run a foreach each aganist every row code
and do it but is it a good practice .
My view model:
function Phone() {
var self = this;
self.Code = ko.observable(""); // this should be unique
self.Date = ko.observable("");
self.PhoneNumber = ko.observable("");
self.Validation = ko.validatedObservable([
self.Code.extend({ required: true }),
self.Date.extend({ required: true }),
self.PhoneNumber.extend({ required: true })
]);
}
function PhoneViewModel() {
var self = this;
self.PhoneList = ko.observableArray([new Phone()]);
self.remove = function () {
self.PhoneList.remove(this);
};
self.add = function () {
self.PhoneList.push(new Phone()); // i add on click of add button
};
}
ko.applyBindings(new PhoneViewModel());
Any suggestions are appreciated .
Upvotes: 0
Views: 1453
Reputation: 2307
Add the following jQuery in $(document).ready(function(){});
, and it will show you the repeated text fields:
$(document).ready(function () {
$("input:submit").click(function () {
$("input:text").each(function(){
var index = $(this).index("input:text") % 3;
var value = $(this).val();
$("input:text").not(this).each(function(){
if($(this).index("input:text") % 3 == index && $(this).val() == value && $(this).val()!="")
$(this).next().show().text("Repeated");
});
});
});
});
DEMO (with your fiddle).
Upvotes: 1
Reputation: 338326
First, in your set-up:
// straight from https://github.com/Knockout-Contrib/Knockout-Validation
ko.validation.rules['mustEqual'] = {
validator: function (val, otherVal) {
return val === otherVal;
},
message: 'The field must equal {0}'
};
Later, in PhoneViewModel
:
self.codesAreUniuqe = ko.computed(function () {
var codes = {},
valid = true;
// group by code, count occurrences
ko.utils.arrayForEach(self.PhoneList(), function (phone) {
var code = phone.Code();
codes[code] = codes[code] ? codes[code] + 1 : 1;
valid = valid && codes[code] === 1;
});
return valid;
}).extend({ mustEqual: true });
Upvotes: 1