javascript - 如果其他字段有值(value),则创建必填字段

标签 javascript c# jquery controller asp.net-mvc-5.2

我有这些变量:

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>

Controller :

[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);
 }

如果 BossId 有一个值,在其他作品中,如果 DropDownList 的文本不是“-- Select --”,并且我想进行该验证(我在 Controller ,使用 JavaScript 检查领导日期和特定卖家(老板)的入场日期),我该如何做到这一点?

最佳答案

实现IValidatableObject在您的 View 模型上可以更好地控制像这样的临时验证规则。

示例

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" } );
        }
    }
}

那么您只需在 Controller 操作中检查 ModelState.IsValid 即可。

注意:这仅将服务器端验证应用于 ModelState。如果您还需要客户端验证,则需要实现一个 Javascript 函数,该函数在提交表单之前执行类似的操作。

示例:

$('form').validate({
    rules: {
        HeadShipDate: {
            required: {
                depends: function (element) {
                    return $("#BossId").val() != '';
                }
            }
        }
    },
    messages: {
        HeadShipDate: {
            required: "Please specify the Headship Date"
        }
    }
});

关于javascript - 如果其他字段有值(value),则创建必填字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30511415/

相关文章:

javascript - 在具有不同文本大小的 2 个 div 之间同步滚动

jquery - Web 应用程序上的 QUnit?

javascript - jQuery UI Accordion 在 MVC 4 Debug模式下工作,但不在发行版中工作

c# - 使用在 COMPILE 期间扩展的环境变量值定义常量

c# - 无需解析的干净自然的脚本功能

javascript - 如何在 URL 构建中转义 & 运算符

javascript - 包含 ZeroMQ JS 绑定(bind)时收到“TypeError : zmq. zmqVersion 不是函数”

c# - EntityFramework Code First继承与自定义鉴别器

javascript - 使用 Raphael js 拖放

javascript - reveal.js - 远程控制