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.)

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Dangit, beat me to it by 20 secs!
2
$('#formId').submit(function () {
    var standardIsValid = $(this).validate().form();
    var customIsValid = customValidations();
    if (!standardIsValid || !customIsValid) {
        return false;
    }
});

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.