Validate EmberJS TextField on the fly?
ember.js, html, javascript, validation
Solution
There are a number of ways to do this sort of thing. Here we can accomplish this using bindings and observers.
First lets create a function that will always return a number.
var onlyNumber = function(input) {
return input.toString().replace(/[^\d.]/g, "");
};
Using that we can do the following
App = Ember.Application.create();
App.person = Ember.Object.create({
age: 42
});
App.NumberField = Ember.TextField.extend({
valueBinding: Ember.Binding.from("App.person.age").transform(onlyNumber),
_cleanValue: function() {
this.set('value', onlyNumber(this.get('value')));
}.observes('value')
});
1) We are creating a Binding to the Person's age, but anything that passes through this binding can only be a number. See Ember.Binding to/from transforms for more details.
2) We are observing the text field's value and setting it to be only a number when it changes. If the user enters '42a' we will immediately set it back to '42'. Note that even though '42a' was in the text input for a brief second it would not have been able to pass through the binding because of our transform.
Here is a fiddle showing this example: http://jsfiddle.net/nDBgC/
Problem
I need to validate a form textfield that's bound to a property of a model using EmberJS. I want the user to only be able to type valid, positive numbers. I know of jQuery.isNumber(), but I don't know how to wire it to the field. I tried writing explicit getter/setter functions on the model's property using Ember.computed(...), but it didn't work. Is there something similar to WinForms onChanging() event that I can hook up to?