1

And I want to create my own validator with Backbone.validation.

I have tried this:

_.extend(Backbone.Validation.validators, {
    myValidator: function(value, attr, customValue, model) {
        if(value !== customValue){
            return 'error';
        }
    },
});

And in my schema:

profiles: {
    editorClass: "form-inline test",
    title: "Skills",
    type: 'List',
    itemType: 'NestedModel',
    model: UserProfile,
    render: "buttonsstars",
    validators: ['myValidator'],
},

But, i couldnt get anything.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
  • Are you really using [backbone.validation](https://github.com/thedersen/backbone.validation) or [backbone-forms](https://github.com/powmedia/backbone-forms)? – Emile Bergeron Nov 09 '16 at 17:06
  • sorry but what do you mean?? – Pari Shontelle Riri Nov 10 '16 at 11:22
  • You are extending `Backbone.Validation.validators` which is from [Backbone.validation](https://github.com/thedersen/backbone.validation) but then you're trying to use it in the `validators` property inside a schema, which is unrelated to Backbone.validation and looks like it's from [Backbone-forms](https://github.com/powmedia/backbone-forms) lib. That's why I'm asking if you're confusing the two. – Emile Bergeron Nov 10 '16 at 14:40

1 Answers1

1

From the documentation of backbone.validation, to add a custom validator, you first need to extend the Backbone.Validation.validators (before using it within a model).

_.extend(Backbone.Validation.validators, {
  myValidator: function(value, attr, customValue, model) {
    if(value !== customValue){
      return 'error';
    }
  },
});

Then use it like this:

var Model = Backbone.Model.extend({
  validation: {
    age: {
      myValidator: 1 // uses your custom validator
    }
  }
});

If the custom validator is specific to a model, but shared across the validation schema:

var SomeModel = Backbone.Model.extend({
  validation: {
    name: 'validateName'
  },
  validateName: function(value, attr, computedState) {/*...snip...*/}
});

If the validator is custom for a specific field of the schema:

var SomeModel = Backbone.Model.extend({
  validation: {
    name: {
      fn: function(value, attr, computedState) {/*...snip...*/}
    }
  }
});
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129