Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

asp.net mvc - attaching jquery validation to replacement element

I have an aspnet mvc form with a dropdown list in, that I am replacing with a jquery combobox.

the original dropdownlist has a client validation set against it - using the unobtrusive lib along with the standard jquery validate - , and I would like this validation attached to the combobox instead.

as part of the generation of the combobox, the name is removed from the dropper and instead set on a hidden field. the problem I am facing is that the validation message is then not showing for the combobox (hidden field), when it is invalid (empty in this case).

is there any way of hooking up the hidden field to validate as the dropdown list would have? I have tried a couple of things:

  1. along with setting the name of the hidden field to the dropdown name - copying the data-val and data-val-required attributes over, but I am having no luck with that. I realise that as the hidden field is added dynamically the validator will not pick it up, but figured as the validation selects by name (afaik) it might just work. I have tried to re-parse the form so that it picks up the hidden field, but as the original rule remains - that doesnt seem to work.
  2. I have also tried not using a hidden field and leaving the validation on the original dropper - which when items in the combobox are set , also sets the value in the dropper. this also doesnt work - i presume because the dropdown is hidden because if i leave it showing the validation works fine.

I am using bootstrap jquery combobox, which I have amended slightly to work with option groups

can anyone offer some assistance please?

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The plugin you're using hides the input and replaces it with its own html. By default, jQuery validation does not validate hidden form controls but you can override this behavior by modifying the validator

$.validator.setDefaults({ 
    ignore: [] 
});

Note that if you have other hidden elements that you don't want validated, then you could give the element a class name

$.validator.setDefaults({ 
    ignore: ":hidden:not('.combobox')"
});

Note: Make sure that this script is outside the $(document.ready) function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...