Pregunta

I have a form that have a three field group that on a click of a "Add New" buttom other three field group will be added. That part is working great.

enter image description here

I want to add a validation so all three fields are required in order to add a new group.

For reference here is the code working: http://jsfiddle.net/5g8Xc/

var ContactsModel = function(contacts) {
    var self = this;
    self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function(contact) {
        return { firstName: contact.firstName, fathersLast: contact.fathersLast, country: contact.country };
    }));

    self.addContact = function() {
        self.contacts.push({
            firstName: "",
            fathersLast: "",
            country: ""
        });
    };

    self.removeContact = function(contact) {
        self.contacts.remove(contact);
    };
};

Any clue on how to implement this validation? I was trying to use jquery validation to do that but I think that is possible with KnockoutJS.

Appreciate any advice.

¿Fue útil?

Solución

As stated already, the validation plugin will be the most elegant, less re-inventive solution.

Edit: After commentary implementation utilizing validation plugin

With that aside, you have a couple options.

  • If you are confident the contact object will always contain only required fields, a not very robust implementation would be iterate over the properties of the contact ensuring each has some value.

  • A little more robust, but still lacking the elegance of the plugin, implementation would be to maintain an array of required fields and use that array for validation. You can reference my example for this setup. Essentially, each required property is mapped to observables. Changes made to the value of any observable property triggers (via a subscription) a mutation call for a dummy observable that is used in a computed. This is required since a computed can't call valueHasMutated. The mutation call triggers the computed to reevaluate, thus updating the UI.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top