Use jQuery and jQuery Validate to Validate with Custom Rules and Post Using Ajax if Validated

12/8/2015 7:30:33 PM

Validate a form using jQuery and if everything validates, post the form using Ajax.

<form id="form1">
    <div>First Name: <input type="text" name="firstName" /></div>
    <div>Last Name: <input type="text" name="lastName" /></div>
    <input type="submit" value="non ajax" />
</form>

<form id="form2">
    <div>First Name: <input type="text" name="firstName" /></div>
    <div>Last Name: <input type="text" name="lastName" /></div>
    <input type="submit" value="ajax" />
</form>

<script type="text/javascript">

    var form2_validation_arguments = {
        errorElement: 'ins',
        errorPlacement: function (error, element)
        {
            if ($(element).is(":checkbox"))
            {
                error.insertAfter($(element).parent());
            }
            else
            {
                error.insertAfter(element);
            }
        }
        ,rules: {
            firstName: 'required',
            lastName: 'required',
        }
        ,submitHandler: function (form)
        {
            alert("ajax submnit");

            //call submit ajax method            
        }
    };


    $(document).ready()
    {
        // Validation
        $("#form2").validate(form2_validation_arguments);
    };
</script>