developer033
developer033

Reputation: 24864

Make a required field if the other field has value

I have these variables:

public int? BossId { get; set; }
public DateTime? HeadShipDate { get; set; }

My view:

<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>

Script (What I was trying to make required if BossId has a value):

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

I want to make the HeadShipDate required field IF BossId has a value, in other works, if the text of DropDownList isn't "-- Select --", AND I want to make that validation (that condition I made in controller, checking headship date with admissionDate of that specific seller(Boss)) with JavaScript, how can I make this?

Upvotes: 0

Views: 1618

Answers (1)

kspearrin
kspearrin

Reputation: 10738

Implementing IValidatableObject on your view model allows for greater control over ad-hoc validation rules like this.

Example

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

Then you only need to check ModelState.IsValid in your controller action.

Note: This only applies server side validation to the ModelState. If you want client side validation as well you will need to implement a Javascript function that does something similar prior to submitting the form.

Example:

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

Upvotes: 1

Related Questions