问题
I'm new to knockout so please bear with me.
I'm trying to using mapping plugin to map the Json data received from server to an existing viewModel instance. I'm able to do this without any issue. But in my viewModel I have used validation plugin so as soon as I map data and bind it to the UI, validation kicks and it immediately displays the error info.
Is there way to not to display that error message until submit button is clicked. Or am I doing something wrong?
Here is the Jsfiddle link
For some reason SO is not allowing me submit this question unless accompanied by code so here is the javascript code copied from jsfiddle -
ko.validation.configure({
parseInputAttributes: true
});
var data = { name: null, email: "joe@shmo.com" };
function vm(){
this.name = ko.observable().extend({required:true});
this.email = ko.observable().extend({required:true});
this.validationCheck = ko.validatedObservable(this);
}
var viewModel = ko.mapping.fromJS(data, {}, new vm());
ko.applyBindings(viewModel);
回答1:
One approach you could try is to hide all the validation messages initially and then add function to your viewmodel that shows them again. You would then call that function when the submit button is clicked.
ko.validation.configure({
parseInputAttributes: true
});
var data = { name: "Joe Shmo", email: "joe@shmo.com" };
var validationMapping = {
'name': {
create: function(options) {
return ko.observable(options.data).extend({required: true});
}
}
}
var viewModel = ko.validatedObservable(ko.mapping.fromJS(data, validationMapping));
viewModel().showValidation = function()
{
$$('.validationMessage').set('style', 'display:inline');
return viewModel.isValid();
}
ko.applyBindings(viewModel);
demo: http://jsfiddle.net/bS62w/3/
来源:https://stackoverflow.com/questions/21162590/knockout-validation-after-mapping