Knock out validation for File input control

2,133 views
Skip to first unread message

Mskhan

unread,
Jun 20, 2014, 1:26:56 AM6/20/14
to knock...@googlegroups.com
Hi knock out groups!!

Is there a way to create validation for file input in knock out js by using  custom validations?

Let say max limit size of file input control..

How could i get size of the file to an observable in this case???

ajaykhy...@gmail.com

unread,
Jun 20, 2014, 1:36:51 AM6/20/14
to knock...@googlegroups.com, ajaykhy...@gmail.com
I have a custom binding like this:

  ko.bindingHandlers['fileupload'] = {

            update: function (element, valueAccessor, allBindingsAccessor) {
                var value = ko.utils.unwrapObservable(valueAccessor())
                if (element.files.length && value) {
                    var file = element.files[0];
                    alert(file.size);
                }
            }
        };

and i used it like:

  <input type="file" name="image" id="image" data-bind="fileupload:Filesize" accept="image/*" />

So in this way i could get the file size, but i dont understand how to proceed to validate this in my model???

 this.Filesize = ko.observable(); ?? It will give empty everytime!!!

Rakesh R

unread,
Jun 20, 2014, 1:56:19 AM6/20/14
to knock...@googlegroups.com, ajaykhy...@gmail.com
Custom binding is one option, other than that, you can do in  a following way,
<input type="file"  data-bind="event: {change: changeMethod}">

Now in that changeMethod form the event argument you can get the files.
self.changeMethod = function(data, event)
{
self.file (event.currentTarget.files[0]);
self.fileSize(event.currentTarget.files[0].size);
}

In this way you can validate on the model value also.

Regards,
Rakesh

Ms

unread,
Jun 20, 2014, 2:43:51 AM6/20/14
to knock...@googlegroups.com

Thanx Rakesh!! this way helped me!!!


ajaykhy...@gmail.com

unread,
Jun 20, 2014, 2:47:18 AM6/20/14
to knock...@googlegroups.com, ajaykhy...@gmail.com


By the way could you please help me with another validation in knock out???
 

aru...@tripmakers.com

unread,
Nov 29, 2016, 6:39:07 AM11/29/16
to KnockoutJS, ajaykhy...@gmail.com
How to validation image dimension in knock out?
Reply all
Reply to author
Forward
0 new messages