I have a form where say I have 2 controls. A select control which has been customized using bootstrap-selectpicker and a textbox which are strongly typed with a viewmodel. Below are the details of the project structure and here is the DEMO and validation is using jquery-validate
SampleViewModel.cs
public class SampleViewModel
{
[Required(ErrorMessage="Please Select a Role")]
//Not sure whether Required has to be assigned to RoleId or Roles
public int RoleId { get; set; }
public SelectList Roles { get; set; }
[Required(ErrorMessage="Please Enter a name")]
public string name{get;set;}
}
View
<div class="container">
<div class="col-md-6 col-md-offset-3">
<h1>Hello Stranger</h1>
@using (Html.BeginForm("", "", FormMethod.Post,
new { enctype = "multipart/form-data", id="frmSample" }))
{
<div class="form-group">
@Html.DropDownListFor(m => m.RoleId, Model.Roles, "Please Select your Country", new{@class="selectpicker"})
@Html.ValidationMessageFor(m=>m.RoleId)
</div>
<div class="form-group">
@Html.TextBoxFor(m => m.name, null, new{@class="form-control"})
@Html.ValidationMessageFor(m=>m.name)
</div>
<button type="button" class="btn btn-success submit">Ask</button>
}
<br/><br/>
</div>
</div>
Controller
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
SampleViewModel model=new SampleViewModel();
model.Roles = new SelectList(new string[] { "Admin", "Manager" });
return View(model);
}
}
JS
$(document).ready(function(){
$('.selectpicker').selectpicker();
$("#frmSample").validate({
onfocusout: true
});
});
$('.submit').on('click',function(){
if($("#frmSample").valid())
alert(true);
});
Problem
- The problem I am facing is my
dropdownelement doesn't get validated usingjquery validationwhereas mytextboxgets validated. May be the problem is the way I am initializing or assigning theRequiredattribute to the particularmodelattribute and I am not sure for which one to assign therequiredattribute. - I have given
onfocusout:trueto validate on focus out but unless you type something ontextboxand delete the content, the validation doesn't happen
Any help on this is highly appreciated.
.selectpicker()I assume is a jquery plugin, which will be hiding the<select>element and replacing it with its own html. You need to modify the validator to validate hidden inputs (by default they are not). And the[Required]attribute is correct on theRoleIdproperty :)ignore: []on validation according to this question and answers but still this isn't helpful.. :(@Html.ValidationMessageFor(m=>m.Roles)- it should beRoleId