mlaccetti
mlaccetti

Reputation: 1756

Field and Form Validation with ember.js

I've integrated Boronine's excellent field validation code for ember.js from jsfiddle. While that is wonderful, I still need to perform form level validation, to ensure that when the user submits the form, everything is okay.

What's the best way to do that? Is there a way that I can mark a field as having been validated, so that the form handler can simply walk the fields to see what has been validated or not?

MP.SignUpFormView = Em.View.extend({
    submitLogin:function (event) {
        // walk through object fields to perform validation here, but how?!
    }
});

Edit:

For clarity, I am using Handlebars and binding, not trying to walk DOM objects or the like.

Upvotes: 2

Views: 4943

Answers (1)

Trek Glowacki
Trek Glowacki

Reputation: 3621

The pattern you're trying to use makes sense in applications that follow a document-scripting pattern, which Ember does not. You can force this work, but you'll find each next step in the application will get harder and harder.

In Ember display is backed by data objects so form fields in an Ember application are bound to a property on some object and as changes are made, the values are updated immediately. You don't even really need a <form> except maybe for styling.

When a user wants to take some action on this object (like persisting it to a server) the application's current state will answer the question "what happens when a user wants to take this action right now?" A user clicking a button here doesn't mean "now serialize the data in the form and do something" it means "I'm done changing the properties of this object and would like to do something else in the application now."

Your handlebars template would look something like this:

{{view Ember.Textfield valueBinding="name"}}
{{view Ember.Textfield valueBinding="age"}}

<button {{action save content}}>Save</button>

And a possible state in your application where this can be handled

Ember.Route.extend({
  save: function(router, event){
    if (event.context.validate()){
      router.transitionTo('someNewState')
    }
  }
})

Upvotes: 5

Related Questions