-
Notifications
You must be signed in to change notification settings - Fork 0
/
backboneValidation1.html
113 lines (98 loc) · 2.2 KB
/
backboneValidation1.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<!DOCTYPE html>
<html>
<head>
<title>Backbone validation tests</title>
<style type="text/css">
.invalid {
border: 1px solid red;
}
span.err {
color: red;
font-style: italic;
font-weight: bold;
}
</style>
<script type="text/javascript" src="lib/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="lib/underscore-min.js"></script>
<script type="text/javascript" src="lib/backbone-min.js"></script>
<script
type="text/javascript"
src="lib/backbone-validation-min.js"></script>
<script type="text/javascript">
_.extend(Backbone.Validation.callbacks, {
//this actually shows errors
valid: function (view, attr, selector) {
var $el = view.$("#" + attr);
$el.removeClass("invalid");
var $elErr = view.$("#" + attr + "Err");
$elErr.html("");
},
invalid: function (view, attr, error, selector) {
var $el = view.$("#" + attr);
$el.addClass("invalid");
var $elErr = view.$("#" + attr + "Err");
$elErr.html(error);
}
});
var CustomerModel = Backbone.Model.extend({
defaults: {
name: "",
age: ""
},
validation: {
name: {
required: true,
msg: "need to know you"
},
age: {
min: 18,
msg: "must be adult"
}
}
});
var CustomerView = Backbone.View.extend({
el: "#main",
initialize: function () {
Backbone.Validation.bind(this);
},
events: {
"click #save": "save"
},
save: function (e) {
e.preventDefault();
this.model.set({
name: $("#name").val(),
age: $("#age").val()
});
if (this.model.isValid(true)) {
alert("Success!");
}
}
});
$(document).ready(function () {
new CustomerView({
model: new CustomerModel()
});
});
</script>
</head>
<body>
<form id="main">
<p>
Enter name:
<input id="name" name="name" type="text" /> <span
id="nameErr"
class="err"></span
><br />
</p>
<p>
Enter age:
<input id="age" name="age" type="text" /> <span
id="ageErr"
class="err"></span
><br />
</p>
<input type="button" id="save" name="save" value="Save" />
</form>
</body>
</html>