JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<script src="https://rawgithub.com/fantactuka/backbone-validator/master/backbone-validator.js"></script>
<script src="https://rawgithub.com/NYTimes/backbone.stickit/master/backbone.stickit.js"></script>
<div id="user-form-template">
<h3>Backbone.Validator + Backbone.Stickit + Backbone.Ext example</h3>
<form action="/">
<label for="email">Email</label>
<input type="text" name="email" id="email">
<br>
<label for="address.country">Country</label>
<input type="text" name="address.country" id="address.country">
<br>
<label for="address.city">City</label>
<input type="text" name="address.city" id="address.city">
<br>
<label for="address.street">Street</label>
<input type="text" name="address.street" id="address.street">
<br>
<input type="submit" value="Save" />
<input type="button" class="set-street" value="Set street to 'Jackson Street, 11'">
</form> <pre id="log"></pre>
</div>
CSS
body {
font: normal 14px/18px Arial, sans-serif;
}
label, input, .error-text {
display: inline-block;
margin: 0 10px 15px 0;
}
label {
width: 60px;
}
input {
padding: 3px;
font: normal 14px/14px Arial, sans-serif;
}
.error-text {
color: #900;
}
#log {
font-size: 12px;
line-height: 16px;
}
}
JavaScript
$(function () {
var UserFormView = Backbone.View.extend({
el: $('#user-form-template'),
// Stickit bindings
bindings: {
'input[name="email"]': 'email',
'input[name="address.country"]': 'address.country',
'input[name="address.city"]': 'address.city',
'input[name="address.street"]': 'address.street'
},
events: {
'submit form': 'onSubmit',
'click .set-street': 'onSetStreetClick'
},
render: function () {
this.bindValidation(); // Attach model validation's events to the view
this.stickit(); // Stickit bindings
},
// Using flattened attributes while working with model
onSetStreetClick: function () {
this.model.set('address.street', 'Jackson Street, 11');
return false;
},
// When ready to send model's data - use #toJSON method (for #save it's is called automatically) to
// unflatten attributes into nested object
onSubmit: function () {
var errors = this.model.validate();
$('#log').html(
'Model is valid: ' + (errors ? 'false' : 'true') + '\n' +
'Data: ' + JSON.stringify(this.model.toJSON(), undefined, 2) + '\n' + (errors ? 'Errors: ' + JSON.stringify(errors, undefined, 2) : ''));
// this.model.save() -> will call validation & toJSON for data sending automaticaly
return false;
}
});
var User = Backbone.Model.extend({
// Backbone.Validator configuration
validation: {
email: {
format: 'email',
required: true
},
'address.country': {
required: true
},
'address.city': {
required: true
}
},
initialize: function () {
this.attributes =...