1

In my view I have a button that submits the form:

<input type="button" value="Save Only" id="save" onclick="submitForm('SaveOnly')" />

This is one of a few different buttons, all of which will be handled differently in different Controller Action methods.

Also in the view is this submitForm(action) Javascript method:

function submitForm(action) {
    var form = document.getElementById("myForm");
    form.action = "/Area/MyController/" + action;
    form.submit();
}

When I use a submit button (rather than type="button"), unobtrusive client-side validation works properly. However, when I use this submitForm(action) function, the client-side validation does not happen. How can trigger the client side validation?

2
  • Are any errors showing up in the console? Commented May 13, 2015 at 22:05
  • No. Also the server side validation is working correctly. Commented May 13, 2015 at 22:08

1 Answer 1

2

You can call it manually as follows:

function submitForm(action) {
    var $form = $("#myForm");
    $form.action = "/Area/MyController/" + action;

    $.validator.unobtrusive.parse($form);
    $form.validate();

    if ($form.valid()) {
       $form.submit();
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

I'm getting a console error: form.validate is not a function
@navig8tr I have changed it to use a jQuery selector now instead, please re-try the code above. :)
different console error: Cannot read property 'form' of undefined
Correct the selector to var $form = $("#myForm");
Perfect! Now I can go home happy. :-)
|

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.