Chris
Chris

Reputation: 3657

Emberjs live serverside validation

I've managed to get the input going to my server, and the server responding if the input is valid, or returning an error object if not.

I'm just not sure how to use the returned error object to actually do something. There are many examples around the internet of how to loop through the error object and display the message but that isn't exactly what I'm after.

I have a form component which has a bunch of fields that look like:

{{input type="text" value=account.twitterId class="input" focus-out="validateInput"}}

and validateInput in the component looks like

validateInput() {
  let account = get(this, 'account');

  account.save().then(() => {
    console.log('success!'); // add class to the input field
  }).catch((adapterError) => {
    console.log(account.get('errors')); // add different class to the input field
    console.log(adapterError);
  });
},

As mentioned above, this triggers and either returns successful or error message

But how do I take the result and use it to add classes to the class key of the input field?

I did attempt with the following

  hasError: false,

  actions: {

  validateInput() {
    let account = get(this, 'account');

    account.save().then(() => {
      set(this, 'hasError', false);
    }).catch((adapterError) => {
      set(this, 'hasError', true);
    });
  },

}

And then a if statement in the front, which kind of worked but didn't re-trigger if the user changes the input for a second time.

Am I supposed to use a computed property for this? If so how would one look?

Upvotes: 0

Views: 58

Answers (1)

Chad
Chad

Reputation: 395

Your plan should work. I've created an Ember Twiddle that you can use as a reference. I tweaked the model a little to allow for random success / failure promises coming back from a save() method, but the rest is pretty identical to what you posted. Open your console while tabbing out of the twiddle to see the result of the promise being returned. I use a template conditional like you recommended to hide/show some feedback to the user.

https://ember-twiddle.com/3398d28381a4c0afb71cb5d59f271e36

Let me know if you have any questions between your implementation and what I have in the twiddle. ✌🏽

Upvotes: 2

Related Questions