Hi @AHSAN ALI,
I want to remove validation message on this form field on condition base
You just need to make a judgment based on the conditions. You need to describe your needs in more detail so that we can better help you.
You can refer to the example below to decide whether to add a verification message based on the checkbox.
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Test</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control", id = "txtName" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control", id = "txtDateOfBirth" } })
@Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input data-val="true" id="GetNewsletter" name="GetNewsletter" type="checkbox" value="true" />
<input type="submit" value="submit" class="btn btn-default" />
</div>
</div>
</div>
}
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
jQuery(function ($) {
$('form').validate({
rules: {
txtDateOfBirth: {
required: true
}
}
});
$("#GetNewsletter").change(function () {
var checked = $(this).prop("checked");
if (checked) {
$('#txtDateOfBirth').rules('add', { //set required rule
required: true,
messages: {
required: "DateOfBirth is required."
}
});
} else {
$('#txtDateOfBirth').rules('remove', 'required'); //remove rule and call valid()
$('#txtDateOfBirth').valid();
}
});
});
</script>
Best regards,
Lan Huang
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.