Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 2 jQuery validation & ajax form

I want to use jQuery ($.post) to submit my html form, but I want to use the client side validation feature of MVC 2. Currently I hook up the post function to the "OnSubmit" event of the form tag, but I can't hook into the validation, ideally I want to be able to do

if (formIsValid) {
     $.post('<%=Url.Action("{some action}")%>'...
}

Please note, Client side validation is working with jQuery.validation, I just can't get it to test if the validation was successful or not before I post my data.

Andrew

The final solution

<%
    Html.EnableClientValidation();
    using (Html.BeginForm("Register", "Account", FormMethod.Post, new { id = "registrationForm" })) {
%>
...
<button type="submit" onclick="return submitRegistration();">Register</button>
<%
    }
%>



<script type="text/javascript">
  function submitRegistration() {
    if ($("#registrationForm").valid()) {
      $.post('<%=Url.Action("{some action}")'...
    }
    // this is required to prevent the form from submitting
    return false;
  }
</script>
like image 621
Andrew Boyd Avatar asked Nov 05 '22 05:11

Andrew Boyd


1 Answers

You can initiate jQuery validation on the button click event. Place the following inside your button-click event-handler:

if ($('form').valid())
   //take appropriate action for a valid form. e.g:
   $('form').post('<%=Url.Action("{some action}")%>')
else
   //take appropriate action for an invalid form

See the Validation plugin documentation for more information.

like image 171
MJ Richardson Avatar answered Nov 09 '22 14:11

MJ Richardson