主干仅在保存中验证单个属性

backbone validate single attribute in save only

本文关键字:验证 单个 属性 保存      更新时间:2023-11-18

我有一个具有两个属性的模型。让我先解释一下。

Backbone.Model.extend({
    validation: {
            username: [
               {required: true, msg: 'Enter email/username.'},
            ],   
            password: [
               {required: true,msg: 'Enter password.'}, 
               {minLength:20,msg: 'Incorrect password length.'}]
        },
}); 

我想验证保存函数中的单个属性。你知道吗?意思是,如果我的用户名&密码字段为空,则应仅针对用户名发生错误。

我正在使用主干网。使用主干网进行验证。

感谢

要使用Backbone.Validation验证单个或多个属性,请使用以下代码:

yourModel.isValid('username') // or
yourModel.isValid([ 'attribute1', 'attribute2' ])

有两种方法可以使用:

方法1

我认为最简单的方法是在验证用户名之前不设置密码字段。引用常见问题解答:

什么时候得到验证?

如果使用Backbone v0.9.1或更高版本,则将验证模型中的所有属性。然而,如果从未设置过(显式或使用默认值)实例名称,则在设置该属性之前不会对其进行验证。

这在填充表单时验证表单时非常有用,因为您不想提醒用户尚未输入的输入错误。

如果需要验证整个模型(两个属性都已设置或未设置),可以对模型调用validate()或isValid(true)。

所以,不要对整个模型调用validate。首先调用用户名字段,然后调用密码字段。

此外,在验证用户名之前,不要在模型中设置密码字段。

方法2

另一种方法是使用FAQ:中描述的条件验证

您支持条件验证吗

是的,嗯,有点。您可以通过将所需的验证器指定为函数来进行条件验证。

因此,您的代码可能看起来像:

Backbone.Model.extend({
    validation: {
            username: [
               {required: true, msg: 'Enter email/username.'},
            ],   
            password: [
               {required: function(val, attr, username) {
                   return Bool(username); //some code here- return true if username is set, false if it is not. This rough example may not work in the real world.
               },msg: 'Enter password.'}, 
               {minLength:20,msg: 'Incorrect password length.'}]
        },
}); 

我很确定这就是Ulugbek Komilovich的建议,尽管我不确定答案中的语法是否正确。

M = Backbone.Model.extend({
    validation: {
      username: [
        {required: true, msg: 'Enter email/username.'},
      ],   
      password: function(value, attr, computedState) {
        // new M(this.get('username')); //or use second way
        if(this.get('username')) {
          return 'Enter email/username.';
        }
        // other checks
      }
    },
});