![](/img/trans.png)
[英]how to make required to an input field if field has default value using validate plugin
[英]Make a required field if the other field has value
我有这些变量:
public int? BossId { get; set; }
public DateTime? HeadShipDate { get; set; }
我的观点:
<div class="form-group">
@Html.LabelFor(model => model.BossId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("BossId", null, "-- Select --", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.BossId, "", new { @class = "text-danger" })
</div>
</div>
<div id="divDate" class="form-group">
@Html.LabelFor(model => model.HeadShipDate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.HeadShipDate, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.HeadShipDate, "", new { @class = "text-danger" })
</div>
</div>
脚本(如果BossId具有值,我试图将其设置为必需):
<script type="text/javascript">
HeadShipDate: {
required: {
depends: function(element){
return $("#BossId").text() != '-- Select --';
}
}
}
</script>
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Acronym,Percentage,BossId,HeadShipDate")] Department department)
{
Seller boss = db.Sellers.Find(department.BossId);
if (boss.AdmissionDate > department.HeadShipDate)
ModelState.AddModelError(string.Empty, "Headship Date (" + department.HeadShipDate.Value.ToShortDateString() + ") must be greater than the Admission Date (" + boss.AdmissionDate.ToShortDateString() + ") of boss");
else if (ModelState.IsValid)
{
boss.DeptId = department.Id;
db.Departments.Add(department);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.BossId = new SelectList(SellersNonBosses(), "Id", "Name", department.BossId);
return View(department);
}
我要在HeadshipDate必填字段中设置BossId是否为值,在其他作品中,如果DropDownList的文本不是“-Select-”,并且我要进行验证(我在控制器中进行的检查,请检查入职日期和使用JavaScript的那个特定卖方(老板)的日期,我该如何做?
在视图模型上实现IValidatableObject可以更好地控制此类临时验证规则。
public class Department : IValidatableObject
{
public int? BossId { get; set; }
public DateTime? HeadShipDate { get; set; }
...
public IEnumerable<ValidationResult> Validate( ValidationContext validationContext )
{
if( BossId.HasValue && !HeadShipDate.HasValue )
{
yield return new ValidationResult( "HeadShipDate is required if BossId is selected.", new[] { "HeadShipDate" } );
}
}
}
然后,您只需要在控制器操作中检查ModelState.IsValid
。
注意:这仅将服务器端验证应用于ModelState。 如果还需要客户端验证,则需要实现一个Javascript函数,该函数在提交表单之前会执行类似的操作。
例:
$('form').validate({
rules: {
HeadShipDate: {
required: {
depends: function (element) {
return $("#BossId").val() != '';
}
}
}
},
messages: {
HeadShipDate: {
required: "Please specify the Headship Date"
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.