简体   繁体   中英

Knockout validation for select element appears on page load

I'm having the exact same problem as described in this question . But the accepted solution does not solve the problem.

Here's my form element markup:

<select
    class="form-control"
    data-bind="options: industries, optionsText: 'description', optionsValue: 'code', optionsCaption: 'Choose...', value: industry_code"
></select>

My data looks like this:

[
    {"code":"00","description":"Unclassified","parent":null},
    {"code":"01","description":"Amusement\/Arcade","parent":null},
    ...
];

And I'm trying to make this field required with the following code:

self.industry_code.extend({
    required: { message: "Please select an industry." }
});

It works perfectly for selecting, updating, etc. but when I load the form for the first time, the "Please select an industry." message appears. None of my other knockout validation code (for <input type='text'> elements) does this, so I'd like this one to behave the same way.

I did try the solution mentioned in the question cited above (in fact, I was already using the optionsCaption binding). Maybe the I'm missing a step... the answer to the previous question is vague to the point of being almost useless.

Has anyone else solved this problem?

The solution for your problem is quite easy. When you first initial your viewModel you need to call this instruction

self.Errors.showAllMessages(false)

This will disable all the errors on first load. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM