问题
I have a view that is rendered dynamically. It may have some inputs or may not have.
After a user fills everything and tries to send data I call this.model.isValid(true)
( or this.model.isValid()
) and it returns false
even if the data from inputs is valid.
I think the cause is Backbone Validation tries to validate attributes of inputs we did not render.
Is there any solution to skip model attributes if we have no sticked elements of a view?
UPDATE:
My model is similar to this:
MyApp.module("RecordModel", function (RecordModel, MyApp, Backbone) {
RecordModel.recordModel = Backbone.Model.extend({
validation: {
inn: {
pattern: 'inn',
msg: MyApp.messages.inn
},
bik: {
pattern: 'bik',
msg: MyApp.messages.bik
},
uin: {
pattern: 'uin',
msg: MyApp.messages.uin
},
sum: {
pattern: 'sum',
msg: MyApp.messages.sum
}
}
});
});
Bindings:
bindings: {
'#uin': {
observe: 'uin',
setOptions: {
validate: true
},
events: MyApp.Validation.events.inputEvents
},
'#bik': {
observe: 'bik',
setOptions: {
validate: true
},
events: MyApp.Validation.events.inputEvents
},
'#inn': {
observe: 'inn',
setOptions: {
validate: true
},
events: ParkingMate.Validation.events.inputEvents
},
'#sum': {
observe: 'sum',
setOptions: {
validate: true
},
events: MyApp.Validation.events.inputEvents
}
}
So for some reason we din't render #sum
input for instance. As we haven't it got in our DOM, it doesn't exists in RecordModel
, but backbone still tries to validate it. Or if we have this input in our DOM, everything works fine.
回答1:
How can I allow empty values but still validate if the user enters something?
By default, if you configure a validator for an attribute, it is considered required. However, if you want to allow empty values and still validate when something is entered, add
required: false
in addition to other validators.validation: { value: { min: 1, required: false } }
If you can't let empty values (like at creation), Backbone.validation overrides isValid adding features to the default behavior. What's interesting is the array parameter we can pass:
// Check if name and age are valid var isValid = model.isValid(['name', 'age']);
With this, we can then validate only the fields that exist within the model at the moment:
model.isValid(_.keys(model.attributes));
来源:https://stackoverflow.com/questions/41040915/skip-validation-of-model-attribute-using-backbone-validation