Reputation: 99
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.
Upvotes: 1
Views: 491
Reputation: 17430
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...*/}
}
}
});
Upvotes: 1