How Can I disable button after submit form with model validation in asp.net core?
code:
<form action="/AddComment" method="post" id="InsertCommentForm">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<input type="hidden" asp-for="ProductId" />
<input type="hidden" asp-for="ParentId" value="" id="reply" />
<input asp-for="Email" id="Email" class="form-control mrg15B" placeholder="لطـفا یک ایمیل معتبر وارد کنید">
<span asp-validation-for="Email" class="text-danger"></span>
<input asp-for="FullName" id="FullName" class="form-control mrg15B" placeholder="لطـفا نام خود را وارد کنید">
<span asp-validation-for="FullName" class="text-danger"></span>
<textarea asp-for="Text" id="Text" class="form-control mrg15B area" cols="60" rows="5" placeholder="لطفا متن پیام را وارد کنید"></textarea>
<span asp-validation-for="Text" class="text-danger"></span>
<br />
<input type="submit" value="ارسال" id="InsertCommentBtn" class="btn btn-warning">
</div>
</form>
I tested several times, but if the validation model starts working and prevents the form from being posted, the Disable button remains.
Thankyou
You need use validate() method in jquery.validate.js(the js file has been referenced in _ValidationScriptsPartial.cshtml by default) to validate the form. Only when the validation passed, the button would be disabled:
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$("#InsertCommentForm").on("submit", function(event) {
var validator = $("#InsertCommentForm" ).validate();
var flag = validator.form();
if(flag)
{
$('input[type="submit"]').attr('disabled',true);
}
});
</script>
}