gpt4 book ai didi

knockout.js - 如何在 knockout 验证中验证模型

转载 作者:行者123 更新时间:2023-12-05 00:29:24 25 4
gpt4 key购买 nike

我创建了一个 View 模型,并希望使用 knockout validation 来验证该模型。这是我的 View 模型

function SignInViewModel() {
var self = this;

self.userName = ko.observable('').extend({
required: true,
pattern: {
message: 'Username must be a valid email address',
params: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
}
});

self.password = ko.observable('').extend({
required: true,
pattern: {
message: 'Password must be alpha numeric and 4-8 character long .',
params: /^(?=.*\d).{4,8}$/
}
});

self.login = function () {
// Want to call validate function here
$.post("/account/login", { "userName": self.userName(), "password": self.password() })
.done(function (result) {
redirect(result.redirect);
});
}
}

ko.validation.configure({
decorateElement: false,
errorElementClass: "error", // class name
insertMessages: false,
grouping: { deep: true, observable: true }
});

我想在调用登录功能时验证我的模型。

最佳答案

创建一个验证组,例如

self.errors = ko.validation.group(self);

添加一个计算
self.canLogin = ko.computed(function() {
return self.errors().length === 0;
});

在您的 View 中,将此数据绑定(bind)添加到您的按钮
data-bind="click: login, enable: canLogin"

关于knockout.js - 如何在 knockout 验证中验证模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17298469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com