Models

AJAX Abstraction for a Single Resource

validate

The validate() method can be used to validate whether the attributes provided to a model are valid.

This method does nothing by default, and it's rare that you would need it.

Default Implementation

The default implementation looks like this:

// Run validation against the next complete set of model attributes,
// returning `true` if all is well. Otherwise, fire an `"invalid"` event.
validate: function(attrs, options) {
  // does nothing
}

Usage

Let's say you you're creating a tweet, and for some reason, a tweet is considered invalid if the text property is equal to "Some old tweet".

You could use the validate() method to check for that like this:

import { Model } from 'lore-models';

const Tweet = Model.extend({
  validate: function(attributes, options) {
    if (attributes.text === 'Some old tweet') {
      return 'Text is invalid';
    }
  }
})

const t1 = new Tweet({
  text: 'Some old tweet'
})
const t2 = new Tweet({
  text: 'Some new tweet'
})

The validate() method will be executed when the tweet is created, or when attributes are updated via the set() method.

You can check if the tweet is considered valid by inspecting the validationError property.

In this case, t1.validationError will return 'Text is invalid', because that's what the validate() method returned. On the other hand, tw.validationError will return null, because there was no validation error.