0

I am trying to make simple DropDownList validation (clear jQuery - no unobtrusive) in my ASP.NET MVC 4 application.

I have fields in model:

[DisplayName("Wybierz płatnika")]
public virtual int? studyPayerId { get; set; }
public virtual IList<StudyPayer> PayersList { get; set; }

Then in controller I do:

var payers = RisDbPersistanceManager.RetrieveEquals<StudyPayer>("IsActive", true); 
if (payers != null)
{
  model.PayersList = payers;  // it is populated                 
}
model.studyPayerId = null;

And in my View:

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>

...

$('#studyPayerId').rules('add',
{
    required: true,
    messages: {
        required: "Proszę wybrać płatnika!"
    }
});    
...
<div class="formsElement" >
  <div class="formsElementLabel" >
    @Html.LabelFor(x => x.studyPayerId)
  </div>
  <div class="formsElementInput" >
    @Html.DropDownListFor(x => x.studyPayerId, new SelectList(Model.PayersList, "Id", "Name", Model.studyPayerId), "-- wybierz płatnika --")
    @Html.ValidationMessageFor(x => x.studyPayerId)
  </div>
</div>

In simple TextBox fields everything works - validates my field on Submit button click. But DropDownList does not display any message when I did not choose anything and leave "-- wybierz płatnika --" selection.

EDIT

  <select id="Gender" class="error" name="Gender" style="display: none;">
  <label class="error" for="Gender">Proszę wybrać płeć!</label>
  <div id="Gender_chosen" class="chosen-container chosen-container-single chosen-container-single-nosearch" style="width: 127px;" title="">
    <a class="chosen-single" tabindex="-1">
    <span>-- nieokreślona --</span>
  <div>
  </a>
  <div class="chosen-drop" style="top: 34px; bottom: auto;">
</div>

1 Answers1

2
  1. This is JavaScript so you'll need to show us the RENDERED and relevant HTML code as seen by the browser, not your model, view or controller. Since I cannot see your rendered HTML, I use generic naming in my demo code below.

    • The first option element must have a value="" attribute.
    • The select element must have a name attribute even if you don't use it.

  2. I don't see your call to the .validate() method. The plugin must first get initialized with the .validate() method. You cannot use the .rules() method without it.

jQuery:

$(document).ready(function () {

    $('#myform').validate(); // <- INITIALIZE plugin

    $('#studyPayerId').rules('add', {
        required: true,
        messages: {
            required: "Proszę wybrać płatnika!"
        }
    });

});

Rendered HTML:

<form id="myform">
    <select name="myselect" id="studyPayerId">
        <option value="">-- wybierz płatnika --</option>
        <option value="1">option 1</option>
    </select>
    <br/>
    <input type="submit" />
</form>

Working DEMO: http://jsfiddle.net/nwLqdemu/


I do not understand why you're using the .rules() method. Usually that's is only used when rules need to be added and removed dynamically; or when rules get applied to an entire group of elements at once, because that would be too lengthy to be included within the .validate() method.

Otherwise, you'd simply declare rules within the .validate() method upon initialization...

$(document).ready(function () {

    // INITIALIZE plugin

    $('#myform').validate({ 
        rules: {
            myselect: {  // <- NAME attribute
                required: true
            }
        },
        messages: {
            myselect: {  // <- NAME attribute
                required: "Proszę wybrać płatnika!"
            }
        }
    });

});

Working DEMO 2: http://jsfiddle.net/nwLqdemu/1/


Please see the SO Tag Wiki page for a basic demo and hints on proper usage.


EDIT:

Since you never mentioned using the "Chosen" plugin for creating your drop down list, there is no way anyone could have answered this question. However, since the jQuery Validate plugin ignores hidden elements by default, you'll need to change the ignore option to [] in order to "ignore nothing" and validate the element hidden by Chosen.

Community
  • 1
  • 1
Sparky
  • 98,165
  • 25
  • 199
  • 285
  • The problem was there: DropDownList keeps its data in hidden – Sebastian Xawery Wiśniowiecki Jan 28 '15 at 09:23
  • @XaweryWiśniowiecki, how could anyone know the select was being created by Chosen since you never mentioned it in the original question? Furthermore, you are continuing to use jQuery Validate as if you have `unobtrusive` installed. Since you stated that you are not using `unobtrusive`, I've tried to show you how to properly use the plugin. – Sparky Jan 28 '15 at 16:26