Help please understand why the form always turns out valid.

jsfiddle: http://jsfiddle.net/udXL5/629/

I use the backbone-validation plugin and bootstrap modal windows. I write the following validation rules in the model:

APP.DiaryModel = Backbone.Model.extend({ defaults: { title: undefined, desc: undefined }, validation: { title: [ { required: true, msg: 'Поле не может быть пустым' }, { minLength: 3, msg: 'Введите не менее 3 символов' } ], desc: [ { maxLength: 200, msg: 'Введите не более 200 символов' } ] } }); 

After I try to submit a form with an empty #diaryTitle field, I get the following in the console:

is v true true (index): 164 valid r {cid: "c3", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object ...}

That is, it turns out that the form is valid (!). But in reality it is not valid. because the #diaryTitle field is empty

The code responsible for validation in APP.DiariesView:

 events:{ 'click #showAddDiaryModal' : 'showAddDiaryModal', 'click #addDiaryBtn' : 'addDiary' }, addDiary: function() { var titleValue = $.trim(this.$el.find('#diaryTitle').val()), descValue = $.trim(this.$el.find('#diaryDesc').val()); var model = new APP.DiaryModel(); model.set({ title: titleValue, desc: descValue }); console.log('is v', model.isValid(), model.isValid('title'), model.isValid('desc')) if(model.isValid()) { console.log('valid', titleValue, descValue, model) } else { console.log('invalid') }; } 

    1 answer 1

    I assume that this plugin is used for validation.

    Then for model validation you need to add (add mixin) a class of validation to the object model. It can be added to the prototype Backbone.Model , if validation is needed in all models. Or in the prototype APP.DiaryModel , if validation is needed only in this model.

    Example:

    For all models:

     _.extend(Backbone.Model.prototype, Backbone.Validation.mixin); 

    Only for APP.DiaryModel :

     _.extend(APP.DiaryModel.prototype, Backbone.Validation.mixin);