带有动态消息的敲除验证器
我希望我的基因淘汰验证器的消息取决于输入的验证。这似乎是一个非常常见的用例,但我找不到任何方法...这是我喜欢做
ko.validation.rules.dumb = {
validator: function( value )
{
if (value.startsWith( "s")) return {isValid:true}
return {isValid:false, message: value + " needs to start with an s"}
}
}
some_field.extend({dumb: {}});
这种工作的简单示例:
ko.validation.rules.sort_of_works = {
validator: function( value)
{
if (value.startWith("s")) return true;
ko.validation.rules.message = value + needs to start with an s";
return false;
}
}
但是它确实不是't-因为它仅在您只使用该验证器的一个字段时起作用:(
我尝试在函数中访问“此”,但这是验证器函数的this - 这是没有用的,因为它没有也有一条消息。 ) - 我不想一次进行验证,然后再次与
我想要的消息一起 使用。在服务器上 - 但不幸的是,该应用程序的其余部分(不是我写的)并不是真正的设置来支持Isvalidating-因此我不能使用异步。
I want my knockout validator to have a message that depends on the validation of the input. It seems like a very common use case but I can't find any way of doing it... here's a simplistic example of what I'd like to do
ko.validation.rules.dumb = {
validator: function( value )
{
if (value.startsWith( "s")) return {isValid:true}
return {isValid:false, message: value + " needs to start with an s"}
}
}
some_field.extend({dumb: {}});
This sort of works:
ko.validation.rules.sort_of_works = {
validator: function( value)
{
if (value.startWith("s")) return true;
ko.validation.rules.message = value + needs to start with an s";
return false;
}
}
but it really doesn't - because it only works if you only have one field using that validator :(
I tried accessing "this" in the function, but the this is the this of the validator function - which isn't useful, as it doesn't have a message on it. Also - I've seen people make message a function, so it depends on the input itself - but my validation is expensive (think something like parsing, where you want to say exactly where the error is in the string) - and I don't want to do it once for the validation, and then again for the message.
What I want works perfectly with the async validation callback function - in fact that's sort of what I'm mimicking, the validation actually happens on the server - but unfortunately the rest of the app (not written by me) is not really setup to support IsValidating - so I can't use async.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为该库旨在使用
扩展
链多个验证。因此,您没有使用一个一个验证器函数来检查大量情况,而是创建一组验证器,所有验证器都对与单个错误消息相对应的一个简单检查器:
I think the library is designed to chain multiple validations using
extend
.So, instead of having one validator function that checks a ton of cases, you create a set of validators that all do one simple check that corresponds to a single error message: