paulsm4
paulsm4

Reputation: 121649

ASP.Net Core client-side validation: is there a "validation succeeded" DOM event?

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.

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.

Upvotes: 3

Views: 2383

Answers (2)

David Liang
David Liang

Reputation: 21476

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>
}

Upvotes: 0

Transformer
Transformer

Reputation: 7429

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
    }
});

Upvotes: 1

Related Questions