0

On my form asp net MVC c# I have these fields:

  • True/False as checkbox
  • A as TextBoxFor value required
  • B as TextAreaFor value not required

I need when the checkbox True/False is checked:

  • A value >>> not required and disable this field
  • B value >>> required

Can you help me?

My code below

<div class="row">
    <div class="col-md-12">
        <div class="form-group" style="background-color: lightgoldenrodyellow; border:3px solid; font-weight:bold;">
            <h5 style="font-weight: bold; text-indent: 20px;">
                True/False @Html.CheckBoxFor(m => m.Truefalse, true)
            </h5>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-md-3">
        <div class="form-group">
            @Html.LabelFor(m => m.A)
            @Html.TextBoxFor(m => m.A, "{0:dd/MM/yyyy}", new { @Class = "Mytextarea2", placeholder = "A" })
            @Html.ValidationMessageFor(m => m.A, "", new { @class = "text-danger" })
        </div>
    </div>
</div>
<div class="row">
    <div class="col-md-3">
        <div class="form-group">
            @Html.LabelFor(m => m.B)
            @Html.TextAreaFor(m => m.B, new { style = "width: 420px; height: 100px;", placeholder = "B" })
        </div>
    </div>
</div>

2 Answers 2

1

In your model, do not use the [Required] annotation for fields A and B.

In the js, add a onchange event for the checkbox. This code should enable/disable A/B.

When you call the js when you submit the form, write some front end validation code that checks the state of the box and if A/B textboxes are valid.

Lastly, take care of server side validation. There you can check the state of the model, and add similar logic that you wrote in the front end validation.

Sign up to request clarification or add additional context in comments.

Comments

1

In Javascript, on change method of checkbox you can just check weather checkbox is true and if checkbox value is true add disable attribute with the field you want to disable else remove disable attribute with that field.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.