简体   繁体   中英

How to give mandatory field validation for select2 fields in asp.net mvc 4

I am using select2 plugin for select list in my MVC 4.0 project.

But the default validation of MVC fails when we use select2. Sometimes error message occurs for select list but it doesn't get cleared automatically when we select the value from the select list.

Please give me suggestions about any other client-side validation

Following is my project code.

.cshtml

     <div class="editor-field">
        <select id="cityid">
            <option></option>
        </select>
        @Html.ValidationMessageFor(model => model.CityID)
        <script type="text/javascript">
            $("#cityid").select2({
                placeholder: "Select City",
                width: "200px"
            });
        </script>
    </div>

Model code :

    [Required(ErrorMessage="Please select city")]
    public  int CityID { get; set; }

Please help me to solve this problem

Please check this enter link description here

    (function() {
  var $select = $('select').select2({
    placeholder: 'Choose',
    allowClear: true
  });

  /*
   * When you change the value the select via select2, it triggers
   * a 'change' event, but the jquery validation plugin
   * only re-validates on 'blur'
   */
  $select.on('change', function() {
    $(this).trigger('blur');
  });

  $('#myForm').validate({
    ignore: 'input[type=hidden], .select2-input, .select2-focusser'
  });

  $select.rules('add', 'required');
}());

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