0

如何实现 Canjs 的验证?我遇到了一些麻烦。在他们的指南页面上,他们这样做:

Contact = can.Observe({
init : function(){
    // validates that birthday is in the future
    this.validate("birthday",function(birthday){
        if(birthday > new Date){
            return "your birthday needs to be in the past"
        }
    })
}
},{});

但是当我尝试这个时,我没有任何成功。

4

1 回答 1

2

它应该工作。您只需要使用.errors()您的观察实例(小提琴)检索验证错误:

var Contact = can.Observe({
init : function(){
    // validates that birthday is in the future
    this.validate("birthday",function(birthday){
        if(birthday > new Date){
            return "your birthday needs to be in the past"
        }
    })
}
},{});

var dave = new Contact({
    name: 'Dave',
    birthday: new Date(2024, 05, 05)
});

console.log(dave.errors());

您可以在can.Map.validations 文档中找到完整的演练。

于 2013-07-26T19:39:54.850 回答