gpt4 book ai didi

javascript - 主干验证插件不验证

转载 作者:行者123 更新时间:2023-11-30 10:11:11 26 4
gpt4 key购买 nike

我正在使用 Backbone.Validation验证简单表单的插件。下面是我的模型

var BuyerModel = Backbone.Model.extend({
defaults: {
name: '',
age: ''
},

validation: {
name: {
required: true
},
age: {
min: 18
}
},

initialize: function () {
_.extend(Backbone.Model.prototype, Backbone.Validation.mixin);
}

});

下面是我的看法

var BuyerModelFormView = Backbone.View.extend({

events: {
'click [name~="save"]': 'save'
},

initialize: function () {
Backbone.Validation.bind(this);
},

template: _.template('\
<form>\
Enter name:\
<input name="name" type="text" value="<%= name %>"><br>\
Enter age:\
<input name="age" type="text" value="<%= age %>"><br>\
<input type="button" name="save" value="Save">\
</form>\ '),

render: function () {
var html = this.template(this.model.toJSON());
$(this.el).html(html);
},

save: function () {
console.log(this.model.toJSON());
this.model.set({
name: $('[name~="name"]').val(),
age: $('[name~="age"]').val()
});

console.log(this.model.toJSON());
}

});

我是这样用的

    var buyerModel = new BuyerModel();

var buyerModelFormView = new BuyerModelFormView({
model: buyerModel,
el: 'body'
});

buyerModelFormView.render();

当我在表单中输入任何内容并按下回车键时,它会更新模型但不会验证。即使我输入不正确的值(value)模型仍然会得到更新。

我哪里做错了,我该如何解决?

最佳答案

像这样设置强制验证

this.model.set({
name: $('[name~="name"]').val(),
age: $('[name~="age"]').val()
}, {validate: true});

是你想要的吗?

因为Model.set有这样的字符串

// Run validation.
if (!this._validate(attrs, options)) return false;

// Run validation against the next complete set of model attributes,
// returning `true` if all is well. Otherwise, fire an `"invalid"` event.
_validate: function(attrs, options) {
if (!options.validate || !this.validate) return true;

所以如果你没有通过验证 - 它会被忽略

这样检查

$(function(){
var buyerModel = new BuyerModel();

buyerModel.on('change', function(){
console.log('on change', arguments);
});

var buyerModelFormView = new BuyerModelFormView({
model: buyerModel,
el: 'body'
});

buyerModelFormView.render();
});

关于javascript - 主干验证插件不验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26572885/

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