4

I have an ASP.Net Core Razor page that uses Bootstrap and does client-side validation.

The form looks like this:

<form method="post" class="needs-validation" novalidate>
...

_ValidationScriptsPartial.cshtml looks like this:

<environment include="Development">
    <script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
    ...

Everything works fine. If the user fails to enter a required field or enters a number that exceeds the maximum, the form won't submit and the offending field is highlighted in red.

Q: Is there a DOM event triggered on "validation succeeded"?

I would like to execute some Javascript after I know the form is "OK", but before it's actually POSTED to the server.

Thank you in advance!

David Liang
  • 20,385
  • 6
  • 44
  • 70
FoggyDay
  • 11,962
  • 4
  • 34
  • 48

2 Answers2

1

If you want a quick turn-key solution, you can simply include the jQuery Validation Plugin. The valid condition returns true only if its valid.

Answer: you can then rxJs-subscribe to it by sending the data structure or the control in to get the event out using this jquery.observable plugin

Below is how the Jquery Valid works:

Form:


$("form").valid(); 
// or
if($("form").valid()) {
 //VALID continue
}

Control:

$("[name='CountyOfBirth']").valid(); // RETURNS true/false

On Submit: you can also get similar results of the valid event by checking on form submit

$("form").submit(function() {
    if($(this).valid()) {
       //VALID
    } else {
       //ERROR
    }
});
Transformer
  • 6,963
  • 2
  • 26
  • 52
0

You can use jQuery Unobtrusive Ajax with the form in the razor view.

First, you will need to include jQuery Unobtrusive Ajax script:

npm i jquery-ajax-unobtrusive -D  (or --save-dev)

Secondly, you need to enable unobtrusive ajax on your form by adding specific custom data- attributes:

<form method="post" class="needs-validation" novalidate
  data-ajax="true" data-ajax-method="post"
  data-ajax-begin="onFormBegin"
  data-ajax-complete="onFormComplete">

There are other attributes you can use.


Here you can register callbacks, for example, on the beginning and the completion of form submit:

@section scripts {
    <script type="text/javascript">
        $(function() {
            window.onFormBegin = function() {
                // This is the place where you can execute some Javascript 
                // after you know the form is "OK", but before it's actually 
                // POSTED to the server.
            };

            window.onFormComplete = function(request, status) {
                // ...
            };
        });
    </script>
}
David Liang
  • 20,385
  • 6
  • 44
  • 70