Validating Data

Understand the steps to validate the user’s input before saving it to our application's local storage.

As it stands, we can edit a contact and completely erase their first and last names. Our app will process the change, but that’s not the behavior we want to have. Instead, we want to ensure the following:

  • All contacts have first and last names.

  • Last names have at least two letters in them.

In other words, we need to validate our contact data.

Adding the validate function

To validate our contacts, we need to define a validate function on our model. This function will always be called before the model is saved to ensure the data is valid. If the data is invalid, validate will return an array of errors (inspired by Rails):

Get hands-on with 1200+ tech skills courses.