Skip to content

Instantly share code, notes, and snippets.

@garth
Last active February 16, 2017 19:56
Show Gist options
  • Save garth/6595029 to your computer and use it in GitHub Desktop.
Save garth/6595029 to your computer and use it in GitHub Desktop.
Example code for emberjs form validation. Working example can be seen here http://jsbin.com/ifARet/4
<label class="control-label"
{{bind-attr for="view.inputField.elementId"}}>
{{view.label}}
</label>
{{input
typeBinding="view.type"
class="form-control"
placeholderBinding="view.placeholder"
valueBinding="view.value"
viewName="inputField"}}
<span class="help-block">{{view.message}}</span>
App.Focusable = Ember.Mixin.create({
focused: false,
focusIn: function(event) {
this.set('focused', true);
},
focusOut: function(event) {
this.set('focused', false);
},
autofocus: false,
shouldAutoFocus: function() {
if (this.get('autofocus')) {
this.$('input').focus();
}
}.on('didInsertElement')
});
App.AsyncValidation = Ember.Mixin.create({
label: '',
value: '',
statusClass: function () {
if (!this.get('focused') &&
(this.get('showFieldValidation') || this.get('formController.showFieldValidation'))) {
return this.get('isValid') ? 'has-success' : 'has-error';
}
else {
return '';
}
}.property('isValid', 'showFieldValidation', 'formController.showFieldValidation', 'focused'),
classNameBindings: ['statusClass'],
statusMessage: '',
message: function () {
if (!this.get('focused') &&
(this.get('showFieldValidation') || this.get('formController.showFieldValidation'))) {
return this.get('statusMessage');
}
else {
return '';
}
}.property('isValid', 'showFieldValidation', 'formController.showFieldValidation', 'focused'),
showFieldValidation: false,
formController: null,
isValid: false,
// register this field with the form controller
registerFieldWithController: function() {
this.validateField();
var validationFields = this.get('formController.validationFields');
if (validationFields) {
validationFields.pushObject(this);
}
}.on('didInsertElement'),
// turn on field validation info after first focus
enableShowFieldValidaion: function () {
if (this.get('focused') && !this.get('showFieldValidation')) {
this.set('showFieldValidation', true);
}
}.observes('focused'),
// check if the field is valid
validateField: function () {
var value = this.get('value');
var isValid = false;
var self = this;
// Call the specific validation function, passing the
// value to validate and a callback to which the function
// must pass the result of the validation.
this.validate(value, function (isValid, message) {
// Make sure that the value hasn't changed since async validation
if (value === self.get('value')) {
self.set('statusMessage', message);
self.set('isValid', isValid);
}
});
}.observes('value'),
// base validation function, if we get this far then the field is valid
validate: function (value, status) {
status(true, '');
}
});
App.FormController = Ember.Mixin.create({
showFieldValidation: false,
validationFields: Ember.A(),
isFormValid: function () {
return !this.get('validationFields').any(function (field) {
return !field.get('isValid');
});
}.property('[email protected]')
});
<form role="form" {{action "signup" on="submit"}}>
<div class="panel panel-primary">
<div class="panel-heading">Sign up</div>
<div class="panel-body">
{{input-text
label="Name"
placeholder="name"
value=controller.name
formController=controller
required=true
autofocus=true}}
{{input-email
value=controller.email
formController=controller
required=true}}
</div>
<div class="panel-footer">
<button type="submit"
{{bind-attr class=":btn controller.isFormValid:btn-primary:btn-default"}}>
Sign up
</button>
</div>
</div>
</form>
App.InputEmailComponent = App.InputTextComponent.extend({
placeholder: 'email address',
label: 'Email Address',
validate: function (value, status) {
if (!value || value.length === 0) {
this._super(value, status);
}
else if (!value.match("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$")) {
status(false, 'Please enter a valid email address');
}
else {
// Insert AJAX call here:
setTimeout(function () {
status(true, 'Email address available');
}, 1000);
}
}
});
{{partial _input_text}}
App.InputTextComponent = Ember.Component.extend(App.Focusable, App.AsyncValidation, {
classNames: ['form-group'],
type: 'text',
placeholder: '',
required: false,
validate: function (value, status) {
if (this.get('required') && (!value || value.trim().length === 0)) {
status(false, this.get('label') + ' is required');
}
else {
this._super(value, status);
}
}
});
{{partial _input_text}}
App.UserController = Ember.ObjectController.extend(App.FormController, {
name: '',
email: '',
actions: {
signup: function() {
if (this.get('isFormValid')) {
console.log('ready to save');
}
else {
//show all validation info
this.set('showFieldValidation', true);
}
}
}
});
@Pleveck
Copy link

Pleveck commented Feb 16, 2017

could you possibly post your entire file structure for this project?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment