Josh
Josh

Reputation: 7612

Using Knockout Validation when validation rules are not known until runtime

I've got a KnockoutJS app that requires the user to enter their physical address. By default, we provide fields that map to the components of an address in the country we primarily operate in--specifically, we require a US city, state, and ZIP. These fields, along with the "Address" field, are required. This is the typical formulation of a US address.

But we also have a checkbox that allows them to enter an address for any country. If they check that box, we get rid of the city, state, and ZIP boxes, and replace those fields with a "Country" box. They thus have an "Address" and "Country" box, both of which are required. City, State, and ZIP are hidden, and should not be required.

I can't figure out how to setup the validation for this. Essentially, we don't know which of the fields will be required until run-time, when the user indicates if they have a US or non-US address.

How do you do this with Knockout Validation?

Upvotes: 1

Views: 769

Answers (1)

Jeroen
Jeroen

Reputation: 63800

What might help is the onlyIf construct for validation rules. For example, postal codes are not required in Ireland, so you may have a ViewModel like this:

var viewModel = {
    availableCountries : ko.observableArray(["United States", "Canada", "Ireland"]),
    country : ko.observable("United States")
};

viewModel.zip = ko.observable("").extend({ required: { onlyIf: function() { return viewModel.country() !== "Ireland"; }  }});
viewModel.errors = ko.validation.group(viewModel);

In this case any input bound to the zip observable will only be required for US and Canada, but not for Ireland. See this fiddle for a demo of the above.

Upvotes: 0

Related Questions