问题
There are many post on this one which i find not helpful and i need to find out why and how .
I made a fiddle with two controls dropdown and textbox and applied required validation with .extend My fiddle
Question 1 : when i first load my page i get a validation error beside dropdown but not beside textbox ? i am confused why is that .
Question 2 : Ok . its awkward to display a error message on load so i planned to disable error messages display on load . Added this line ko.validation.init({ insertMessages: false }); . By this i got rid of on load error message display . BUT when i click on submit i can't find the error message text beside textbox or dropdwon .
One way or the other dropdown is failing my cause to display error text.
Any feasible approach is much appreciated .
回答1:
If you subscribe to your observables, you will see that
countryis actually set on load by ko, which is not the case for code (demo):self.Code.subscribe(function () { alert("Codes changed"); }); self.country.subscribe(function () { alert("Country has changed"); });This is caused by how
selectis handled (howoptions bindingis handled I believe) and explains why the validation is done oncountry.insertMessages: falsewill hide all messages, then you need to handle them with thevalidationMessage binding.
Simply remove the init value of your observable (demo):
self.Code = ko.observable();
self.country = ko.observable(); // no ""
回答2:
To disable messages on load you need this instruction
self.Errors.showAllMessages(false)
this will disable all message on first load. setting this will not help you
ko.validation.init({ insertMessages: false })
For your first problem, You must be doing this
<select data-bind='blah,validationElement:TextBoxField' >
this will cause it. Hope it helps.
回答3:
Using this is perfect:
ko.validation.group(yourViewModel, { deep: true }).showAllMessages(false);
However it must be done after calling applyBindings:
ko.applyBindings(yourViewModel);
Otherwise it doesn't work.
来源:https://stackoverflow.com/questions/25422260/knockout-dropdown-validation-on-load-required