KnockoutJS动态表单验证 [英] KnockoutJS dynamic form validation

查看:99
本文介绍了KnockoutJS动态表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有三个字段组的表单,单击添加新"按钮,将添加其他三个字段组.那部分效果很好.

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.

我想添加一个验证,因此必须添加所有三个字段才能添加新的组.

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

在这里供参考的是工作代码: http://jsfiddle.net/5g8Xc/

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);
    };
};

有关如何实施此验证的任何线索?我试图使用jquery验证来做到这一点,但我认为使用KnockoutJS可以实现这一点.

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.

感谢任何建议.

推荐答案

如前所述,验证插件将是最优雅,发明最少的解决方案.

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

在评论后实现使用验证插件

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.

稍微强健一些,但仍缺少插件的优雅之处,其实现方式是维护一个必填字段数组,并将该数组用于验证.您可以参考我的示例进行此设置.本质上,每个必需的属性都映射到可观察对象.对任何可观察属性的值所做的更改将触发(通过subscription)对computed中使用的虚拟可观察对象的突变调用.这是必需的,因为计算者无法调用valueHasMutated.变异调用会触发计算结果进行重新评估,从而更新用户界面.

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.

这篇关于KnockoutJS动态表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆