I have this 2 radio buttons based on the radio button selection I should display textbox and also I should validate textbox. If I select the radio button yes and textbox null then I should show the error. With the below code I am only able to show and hide textbox but not able to validate textbox. Please suggest a solution.
Model :
public class CustomerModel
{
[Required(ErrorMessage = "Please select subscribe option")]
public bool Subscribe {get; set;}
public string Email {get; set;}
}
view :
function ShowHideDiv() {
var chkYes = document.getElementById("Yes");
var dvtext = document.getElementById("dvtext");
dvtext.style.display = chkYes.checked ? "block" : "none";
}
$(function () {
warningel = document.getElementById('lbError');
$("#radio").submit(function () {
if ($('#Yes').is(':checked') && !$.trim($('#Email').val())) {
warningel.innerHTML = "Please Enter Email";
return false;
}
});
});
<div class="form-group col-md-12 ">
<label class="required" for="subscribe">Email Subsciption</label>
<span >Yes : <input type="radio" value="Yes" name="Subscribe" id="chkYes" onclick="ShowHideDiv()" /></span>
<span >No : <input type="radio" value="No" name="Subscribe" id="chkNo" onclick="ShowHideDiv()" /></span>
@Html.ValidationMessageFor(model => model.Subscribe)
</div>
<div id="dvtext" style="display: none">
<label for="email" class="required">Enter Email</label>
<div style="width:300px;">
@Html.TextBoxFor(model => model.Email)
<div id='lbError' style="color: red;"></div>
@Html.ValidationMessageFor(m => m.Email)
</div>
</div>