0

In my mvc 3 application, I would like to execute a function when the user tries to submit the form. Within that function I will check a number of fields to determine if the user has provided the necessary data before submission.

How can I hookup a script to be executed when the user tries to submit the form?

(within the custom validate function, I need to check if various checkboxes have been selected and if yes, then additional values are selected from dropdownlists etc.)

MrMVCMan
  • 490
  • 2
  • 7
  • 20

3 Answers3

5

How can I hookup a script to be executed when the user tries to submit the form?

You could subscribe to the .submit event of the form and after calling the standard client side validation call your custom function:

$(function() {
    $('form').submit(function() {
        if (!$(this).valid()) {
            // standard client validation failed => prevent submission
            return false;
        }

        // at this stage client validation has passed. Here you could call your
        // function and return true/false depending on the result of your
        // custom function
    });
});

Another possibility is to write custom validation attributes and hook up a custom adapter as shown in this answer and a similar one.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2
$('#formId').submit(function () {
    var standardIsValid = $(this).validate().form();
    var customIsValid = customValidations();
    if (!standardIsValid || !customIsValid) {
        return false;
    }
});
Martin
  • 11,031
  • 8
  • 50
  • 77
0

In the view (RAZOR or ASPX), you will define a script like you would in html, and in there will be your client-side validation.

For example :

<script>
  //define your script here, ie. $.(#tagtovaildate).validate();
</script>

<html>
  //code
</html>