knockout.js - knockout trim in mvvm validations -
i using knockout mvvm works fine don't want send data containing white spaces server side code. here sample code
//regular customer self.nameforregularcustomer = ko.observable("").extend({ required: { message: 'promotion name required' }, maxlength: { message: 'promotion name can not exceed 100 character', params: '100' } }); self.statusforregularcustomer = 1; //for create mode 1 new self.keywordforregularcustomer = ko.observable("").extend({ required: { message: 'keyword required' }, maxlength: { message: 'keyword can not exceed 100 character', params: '100' } }); self.promotionmsgforregularcustomer = ko.observable("").extend({ required: { message: 'promotion message required' } }); self.promotiondescforregularcustomer = ko.observable("").extend({ required: { message: 'promotion description required' } , maxlength: { message: 'description can not exceed 100 character', params: '2000' } }); //the object stored data entered in observables self.regularcustomerpromotion = { name: self.nameforregularcustomer, description: self.promotiondescforregularcustomer, keywords: self.keywordforregularcustomer, happymessage: self.promotionmsgforregularcustomer, status: self.statusforregularcustomer, promotioncustomertype: self.promotioncustomertype };
i making ajax call folllowing data format
requestpromo = ko.tojson(self.newcustomerpromotion);
but contains data white space want trim before making api call
tried use field level
ko.subscribable.fn.trimmed = function () { return ko.computed({ read: function () { return this().trim(); }, write: function (value) { this(value.trim()); // this.valuehasmutated(); }, owner: });
but discards validations
try creating own tojson method on view-model , strip out unnecessary white-space yourself. knockout has 2 functions tojs , tojson. can use tojs current values javascript object or use tojson string representation.
this off top of head , i'm not sure if works this.
self.prototype.tojson = function(){ var data = ko.tojs(self.newcustomerpromotion); return { name: data.nameforregularcustomer.trim(), description: data.promotiondescforregularcustomer.trim(), keywords: data.keywordforregularcustomer.trim(), happymessage: data.promotionmsgforregularcustomer.trim(), status: data.statusforregularcustomer.trim(), promotioncustomertype: data.promotioncustomertype.trim() }; };
this return object ready serialized ko.tojson sent on wire.
here blog post explaining in greater detail http://www.knockmeout.net/2011/04/controlling-how-object-is-converted-to.html
Comments
Post a Comment