Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hook into error of jQuery validate unobtrusive in MVC 3?

Looking for a way to hook into the client side fail condition for the form.

I need to re-enable a submit button if the validation fails so they can try again.

I found the following: Using unobtrusive validation in ASP.NET MVC 3, how can I take action when a form is invalid? which might work but I was hoping to do this from a central place as the form can be submitted from several places.

Update:

This function seems to work well assuming you have an input tag with the class ".goButton".

<script language="javascript" type="text/javascript">
    $(".goButton").click(function () {
        if (!$(this).closest("form").valid()) {
            return false;
        }
        $(".goButton").after("Please wait...");
        $(".goButton").hide();
    });
</script>
like image 228
David Thompson Avatar asked Jun 27 '11 13:06

David Thompson


People also ask

What does jquery validate unobtrusive do?

Unobtrusive Validation means without writing a lot of validation code, you can perform simple client-side validation by adding the suitable attributes and including the suitable script files. data-val-required=”This is required.”

How do I turn off unobtrusive validation?

You can disable the unobtrusive validation from within the razor code via this Html Helper property: HtmlHelper. ClientValidationEnabled = false; That way you can have unobtrusive validation on and off for different forms according to this setting in their particular view/partial view.

What is validator unobtrusive parse?

validator. unobtrusive. parse(selector) method to force parsing. This method parses all the HTML elements in the specified selector and looks for input elements decorated with the [data-val=true] attribute value and enables validation according to the data-val-* attribute values.


1 Answers

Then you can hook ALL forms from a central place - just be aware all forms will be hooked. Instead of using $("#formId") in the sample, simply use $("form").submit() and that delegate will be called for any form's submit and in that method you can call your validate check and return true (to submit the form) or false to prevent it.

Something like this off the top of my head

$("form").submit(function () {
  if (!$(this).valid()) {
      return false;
  }
  else
  {
      return true;
  }
});
like image 127
Adam Tuliper Avatar answered Oct 19 '22 17:10

Adam Tuliper