Hope everyone is doing great.
I am using some unobtrusive jQuery in my razor pages .NET core 3.1, for form submission:
<form asp-action="/Test" class="frm__action frm__validate" id="form2"
data-ajax-method="post"
data-ajax="true"
data-ajax-success="success"
data-ajax-failure="failed"
data-ajax-loading="#spinner"
data-ajax-loading-duration="2000">
<!-- FORM ROW -->
<div class="form-row">
<div class="form-group col-sm-6">
<label asp-for="@Model.Tests.Name"></label><span class="txt__red">*</span>
<input asp-for="@Model.Tests.Name" type="text" id="txtcname" class="form-control" data-pristine-required="true"
data-pristine-required-message="Please enter your company name.">
<span id="nameExists" hidden></span>
</div>
</div><!-- FORM ROW -->
<!-- FORM ROW -->
<div class="form-row">
<div class="col-12 text-right">
<input type="submit" class="btn box__shadow btn__orange__filled btn__sm" value="Submit">
</div>
</div><!-- FORM ROW -->
</form>
I am using pristine validations for client-side validations and here is the code that's working:
$(".frm__validate").each(function () {
frmID = $(this).attr("id");
var form = document.getElementById(frmID);
// create the pristine instance
pristine = new Pristine(form, defaultConfig, false);
form.addEventListener("submit", function (e) {
e.preventDefault();
// check if the form is valid
var valid = pristine.validate();
if (valid) {
alert("Form is Valid");
}
else {
alert("For is not Valid");
}
});
});
The problem is very simple: whenever I click the Submit button it hits both the action in the Razor Page C# as well as this JS.
But, what I want is for it to first hit the JS to validate the input, then hit the backend code. If anyone can help, it will be appreciated.
Thanks in advance.
You can try to use modal to replace
alert.You add the Submit button in form,it wll hit js to validate and then show message in modal,and if you click the Submit button in modal,you will post the form.Here is a demo:View:
When click submit button,it will hit js validate,and show the message in the modal:
And click the button in modal,the form will post.