我写了这段代码。请帮我完成正确的验证。我正在尝试这个,但验证没有被调用。 我从视图中调用了模型,但它没有被调用。 看看这个。我很遗憾。 请帮忙
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>page1</title>
<meta name="description" content="">
<meta name="keywords" content="">
<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="handlebars.js"></script>
<script src="underscore.js"></script>
<script src="backbone.js" type="text/javascript"></script>
<script type="text/javascript" src="backbone-validation.js"></script>
</head>
<body>
<form action="#">
UserName: <input id="username" type="text" name="username" />
<br />
Password: <input id="password" type="password" name="password" />
<br />
Email: <input id="email" type="text" name="email" />
<br />
<input type="submit" id="register" value="Register" />
</form>
<script type="text/javascript">
$('#register').click(function(){
var myModel = Backbone.Model.extend({
validation: {
username:{
required: true,
msg: 'Please enter Name'
},
email: [{
required: true,
msg: 'Please enter an email address'
},{
pattern: 'email',
msg: 'Please enter a valid email'
}]
}
});
//var myModel = new Backbone.Model();
var MyView=Backbone.View.extend({
initialize: function(){
Backbone.Validation.bind(this);
}
});
});
//var myview=new MyView();
</script>
</body>
</html>
答案 0 :(得分:0)
这里几件事:
validate()
的模型,应使用Backbone.Validation this.model
醇>
以下是包含一些修复的伪代码。试试吧。
var myModel = Backbone.Model.extend({
initialize: function() {
// your model needs to have Validation Methods on it first
_(this).extend(Backbone.Validation);
},
validation: {
username:{
required: true,
msg: 'Please enter Name'
},
email: [{
required: true,
msg: 'Please enter an email address'
},{
pattern: 'email',
msg: 'Please enter a valid email'
}]
}
});
//var myModel = new Backbone.Model();
var MyView = Backbone.View.extend({
events: {
'click #register': 'onRegister'
},
initialize: function(options){
// Check if your this.model is set here
},
onRegister: function() {
// this model is updated
// write your own
// validation will be triggered on save
//
this.model.save();
// or
// this.model.validate();
},
render: function() {
// you need to have a this.model
// on your view in order to perform binding
Backbone.Validation.bind(this);
}
});
var myview = new MyView({model:new MyModel()});
myview.render();
当然,请阅读Backbone.Validation
上的文档