Rendering errors with ember-validations

Hey errybody,
I am fairly new to ember so I’m sorry if this is a dumb question. I am using dockyards ember-validation library and I’m wondering if there is a way to DRY out the error rendering process. Currently errors for a specific property are stored in the errors object, so if I have a name property and it fails a validation errors.name would return me an ember array with a failure message in it.


["name must be at least 5 characters"]

My question is about how to manifest this in the template as a css class. I want to be able apply a specific css class to the invalid input. I can do something like make a property on the controller for each input that returns a css class if the property is invalid e.g.

//in a controller
{
   nameInputCss: function() {
      if (this.get('errors').name.length > 1) {
         // invalid css calss
         return "has-errors"
      }
      else {
         return  ""
      }
   }.property('errors')
}

but this seems like a pretty bad pattern to adopt as you repeat yourself for each input you want to validate. Any advice on how to use the errors object in a clean way? Am I making a silly mistake somewhere and using the library incorrectly?

1 Like

Hi there!

It depends on how you use the nameInputCss but you could do something like this in your template:

<div {{bind-attr class=":form-group model.errors:has-errors" > 
    ... 
</div>

assuming you want to have the class form-group present at all time and has-errors present whenever your model does not entirely validate. You could also have a finer control by binding model.errors."put your property here" instead of model.errors, which would place the has-error class only when this property does not validate.

The syntax I used is explained here

Hope it helps :smile:

1 Like

This is exactly the solution I was looking for. Thanks! :grinning:

great! You’re welcome :slight_smile: