Knockout validation on my dropdown don't work

血红的双手。 提交于 2019-12-01 01:10:10

Just stumbled into this one as well and after some trial and error I found the following:

The validation breaks down because the optionsCaption uses undefined as a value.

Your model apparently uses '' (in my case it was null) Since null != undefined it somehow all breaks down.

Knowing this, there are two solutions:

  1. on the Model set the value to undefined (in your example transport.category(undefined)) and make use of the optionsCaption like you're used to
  2. add a custom empty selectItem yourself and skip optionsCaption (the solution you used)

When you say "clear the dropdown", how can an option be not picked when there are only three options. Could you make the first dropdown item "Choose an item..." so that you know there will always be one item. If the dropdown index is 0, then show your red error message.

Another option would be to show the red error message if the selectedindex is 0 or the itemcount is 0.

Does that help?

Finally I get it working by adding an element with empty id in my categories list:

var categories = [
    { id: '', description: '--Choose--' },
    { id: 1, description: 'Non classé' },
    { id: 2, description: 'Non nucléaire' },
    { id: 3, description: 'Classe II irradié' },
    { id: 4, description: 'Classe III' }];

I don't know why but simply adding optionsCaption: '--Choose--' don't work for the validation. I mean this element is displayed in my dropdown but the validation process don't consider it as a validation error.

I explicitely had to add an element to my list. Then when this element is selected in my dropdown it is marked as red.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!