Skip to content

Instantly share code, notes, and snippets.

@kshep92
Last active February 8, 2017 23:00
Show Gist options
  • Save kshep92/744f199a2b230f04c6e38c541efa3f05 to your computer and use it in GitHub Desktop.
Save kshep92/744f199a2b230f04c6e38c541efa3f05 to your computer and use it in GitHub Desktop.
Some validation and form control behaviours for Polymer
// Forms
// <form is="data-form" action="/users" model="[[user]]" busy="{{sending}}" id="login">
// ...
// <input type="submit" value="Log In" disabled$="[[sending]]" />
// </form>
// this.$.login.validate()
// this.$.login.send().then().catch()
var Form = {
extends: 'form',
properties: {
busy: { type: Boolean, notify: true, value: false, readOnly: true },
model: { type: Object, value: function() { return {}; } }
},
validate: function() {
var nodes = this.querySelectorAll('.form-control');
var allFieldsValid = true;
nodes.forEach((node) => {
if(!node.checkValidity()) {
allFieldsValid = false;
throw `The field ${node.name} is invalid.`
}
});
return allFieldsValid;
},
send: function() {
this.lock();
return new Promise((resolve, reject) => {
return fetch(this.action, { method: this.method || 'post', body: JSON.stringify(this.model) })
.then((data) => { resolve(data); this.release(); })
.catch((data) => { reject(data); this.release(); })
});
},
lock: function() { this._setBusy(true); },
release: function() { this._setBusy(false); },
_setBusy: function(val) { this.busy = val; }
}
var FormControl = {
properties: {
valid: { type: Boolean, value: false, readOnly: true },
validationMessage: { type: String },
validators: { type: Array, value: function() { return []; } }
},
// Named this way to partially implement some of the HtmlInputElement Interface
checkValidity: function() { /* Implement */ },
attached: function() {
this.classList.append('form-control');
},
_setValid: function(val) { this.valid = val; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment