In the last drip we were tasked with adding validations to our new form for creating new Persons records. These validations should match the validations that we used for our edit form. In most cases, it would be ideal to use the same validations and avoid duplication. However, in our case, since we used an addon to handle validations initially, it might be valuable to roll our own solution here. To refresh, we want to validate the presence of firstName, lastName, email, and phone. We want the first name to have a minimum length of 2 characters and the phone should have a minimum length of 10 and a maximum length of 20.

We are going to try and be really explicit with what we are doing here. In our new contacts controller, let's just setup a basic computed property called recordIsInvalid. This computed property will key off of every property that we want to validate. Then we will return a series of functions that will do the actual validations and we will tests that all of those validator functions return true. We will also place a bang in front as this is a recordIsInvalid property.

Finally, we will set up our validator functions. For existence, since we passed in an array, we will just use the JavaScript array's every method to just make sure that every property we passed in exists.

app/controllers/contacts/new.js:

recordIsInvalid: Ember.computed('newFirstName', 'newLastName', 'newEmail', 'newPhone', function(){
  let firstName = this.get('newFirstName');
  let lastName  = this.get('newLastName');
  let email     = this.get('newEmail');
  let phone     = this.get('newPhone');
  return !(this.theyExist([firstName, lastName, phone, email]) &&
           this.minLength(firstName, 2) &&
           this.minLength(phone, 10) &&
           this.maxLength(phone, 20));
}),
theyExist(propertiesArray){
  return propertiesArray.every(item => !!item);
},
minLength(prop, limit){
  return Ember.isPresent(prop) && prop.length >= limit;
},
maxLength(prop, limit){
  return Ember.isPresent(prop) && prop.length <= limit;
},

The last thing we have to do is use our controller's recordIsInvalid computed property to disable the new form's submit button.

app/templates/contacts/new.hbs:

<button class="btn btn-primary" {{action 'submit'}} disabled={{recordIsInvalid}}>Submit</button>

And that will work. Ultimately, we would want to return error messages depending on what item was failing validations.

Prep

This week we are going to look at Ember's runloop. This can be a particularly difficult topic and is something that almost all Ember developers stumble over at some point. Before we get into it, here are some links to help you along the way: