Vue的最佳表单验证实践是什么?我已经在send按钮的disabled属性的验证方法中使用了简单的if树,但即使只有两个字段,也可能已经有许多情况需要验证,如果我有不同的表单,我必须复制很多内容
下面是我对其中一个模式窗口使用的方法:
isCryptoWithdrawalPossible() {
if (this.sendWalletModal.amount || this.sendWalletModal.address) {
if (this.sendWalletModal.amount && !this.sendWalletModal.address) {
this.sendWalletModal.error = this.$t('wallets.wallets.needAddress');
return false;
} else if (!this.sendWalletModal.amount && this.sendWalletModal.address) {
this.sendWalletModal.error = this.$t('wallets.wallets.needAmount')
return false;
}
if (this.sendWalletModal.amount < this.sendWalletModal.method.minAmount) {
this.sendWalletModal.error = this.$t('wallets.wallets.overLimitMinAmount', [this.sendWalletModal.method.minAmount]);
return false;
}
else if (this.sendWalletModal.amount > this.sendWalletModal.method.maxAmount) {
this.sendWalletModal.error = this.$t('wallets.wallets.overLimitMaxAmount', [this.sendWalletModal.method.maxAmount]);
return false;
}
else if (this.sendWalletModal.amount > this.filteredWallets.find( el => el.currencyTitle == this.sendWalletModal.currency).avaliableFunds - this.calculateSendFee(this.sendWalletModal)) {
this.sendWalletModal.error = this.$t('wallets.wallets.insufficientBalance')
return false;
}
else {
this.sendWalletModal.error = '';
return true;
}
} else {
this.sendWalletModal.error = '';
return false;
}
},发布于 2019-08-02 22:06:39
如果您正在寻找第三方库来简单地处理验证,请检查Vuelidate
发布于 2019-08-02 22:38:16
更新2020年1月:这里是vuelidate的一个很好的概述-它有点像vee-validate (我希望有一个非常熟悉vee-validate的人来展示它的更多功能,但作为vuelidate的介绍,我喜欢这个演示文稿)。https://www.vuemastery.com/conferences/connect-tech-2019/vue-form-validation
在github:(https://github.com/vuelidate/vuelidate)。到目前为止,vee-validate得到了更好的支持,但也许vuelidate已经在一段时间内得到了更好的组织。
你也可以看看这个链接:https://laracasts.com/discuss/channels/vue/vue-validator-vs-vee-validate-vs
我们在我工作的地方使用vee-validate,vee-validate的主页在这里:https://baianat.github.io/vee-validate/。这里有一个很好的沙箱示例:https://baianat.github.io/vee-validate/examples/。我建议看一看codesandbox中的标志示例,看看vee- validating如何跟踪它正在验证的字段的更改。它使用date-fns作为默认的日期库(如果你使用moment,这可能会让你担心,但我同时使用date-fns和moment date和vee-validate (我对moment date使用“自定义规则”特性))。一旦将vee-validate应用于各种表单域,您就可以通过调用如下函数来检查是否有任何域发生了更改:
hasChanged: function() {
return Object.keys(this.fields).some(key => this.fields[key].changed);
}我遇到过vee-validate的问题,特别是在日期方面,但它似乎是vue -and更好的验证库之一。在我看来,如果你遇到问题,现在更容易得到答案(这种观点是有偏见的,因为我使用的是vee-validate而不是其他库)。vee-validate的问题之一是,如果您更改了一个字段,然后将其改回原始值,那么该字段仍然被标记为已更改的-so,您必须自己跟踪初始值和当前值。但在许多表单场景中,您无论如何都必须手动跟踪hasChanged,例如,如果您决定查看表单会更改数据的状态(例如,从未查看更改为已查看),那么您将需要手动记录与表单域无关/在表单域之外的"myFormViewed“变量的更改。
https://stackoverflow.com/questions/57325686
复制相似问题