简体   繁体   中英

Knockout.js validation on hidden fields

I am implementing knockout validation for my form, and I want to make a field required only if it is showing. Depending on the selection of other fields in the form, some controls may be hidden by visibility:hidden or display:none. How can I make these fields required only if shown? I have tried this

var name = ko.observable().extend({
        required: {
            onlyIf: function () {
                return ($('#name').is(':visible'));
            },
            message: '*** Required'
        }
    });

But it doesn't seem to work, and I'm not sure if it should (can you write custom logic like that in knockout onlyIf params?).

Thanks for any help.

As mentioned in comments all you need to do is

Declare a observable in ViewModel per say self.nameVisible=ko.observbale() set the value it True/False from anywhere (either from DB or based on other control selection) . Later on you should use the self.nameVisible() in your validations ie with .extend & onlyIf combo to make things(hide/show element+dynamic conditional validation) work .

Html:

<input type="text" data-bind="value:name,visible:nameVisible"/>

viewModel:

var ViewModel = function () {
    var self = this;
    self.nameVisible = ko.observable(true); //Set it dynamically 
    self.name = ko.observable().extend({
        required: {
            message: '*** Required',
            onlyIf: self.nameVisible
        }
    });
};
ko.applyBindings(new viewModel());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM