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" ></div>
<div >
<input type="hidden" asp-for="ProductId" />
<input type="hidden" asp-for="ParentId" value="" id="reply" />
<input asp-for="Email" id="Email" placeholder="لطـفا یک ایمیل معتبر وارد کنید">
<span asp-validation-for="Email" ></span>
<input asp-for="FullName" id="FullName" placeholder="لطـفا نام خود را وارد کنید">
<span asp-validation-for="FullName" ></span>
<textarea asp-for="Text" id="Text" cols="60" rows="5" placeholder="لطفا متن پیام را وارد کنید"></textarea>
<span asp-validation-for="Text" ></span>
<br />
<input type="submit" value="ارسال" id="InsertCommentBtn" >
</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
CodePudding user response:
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>
}
