1

I am having some troubles with validation using jquery to post a forms data to a controller.

This code works and validation happens fine if I dont use jquery to make the post.

<div id="window">
@using (Html.RequiredFieldsMessage()){}
@using (Html.BeginForm("","",FormMethod.Post,new{id="card-payment"}))
{
    @Html.ValidationSummary(true, "Please fix the errors below.")
    <div class="inputForm no-border">
        <div class="fr">
            @Html.LabelFor(model => model.DpsPaymentModel.CardHolderName)
            @Html.EditorFor(model => model.DpsPaymentModel.CardHolderName)
            @Html.ValidationStyledMessageFor(model => model.DpsPaymentModel.CardHolderName, false)
          </div>
        <div class="fr">
            @Html.LabelFor(model => model.DpsPaymentModel.CardNumber)
            @Html.EditorFor(model => model.DpsPaymentModel.CardNumber)
            @Html.ValidationStyledMessageFor(model => model.DpsPaymentModel.CardNumber, false)
        </div>
        <div class="fr">
            @Html.LabelFor(model => model.DpsPaymentModel.DateExpiry)
            @Html.EditorFor(model => model.DpsPaymentModel.DateExpiry)
            @Html.ValidationStyledMessageFor(model => model.DpsPaymentModel.DateExpiry, false)
        </div>
        <div class="fr">
            @Html.LabelFor(model => model.DpsPaymentModel.Cvc2)
            @Html.EditorFor(model => model.DpsPaymentModel.Cvc2)
            @Html.ValidationStyledMessageFor(model => model.DpsPaymentModel.Cvc2, false)
        </div>
        <div class="fr">
            @Html.LabelFor(model => model.DpsPaymentModel.Amount)
            @Html.EditorFor(model => model.DpsPaymentModel.Amount)
            @Html.ValidationStyledMessageFor(model => model.DpsPaymentModel.Amount, false)
        </div>
        <div class="fr">
            <button type="submit" id="process-payment">Submit</button>
        </div>
    </div>

}
</div>

If I add this to my view. The validation is always returned as true. My html is not in a partial view its in the same view that loads the correct jquery validation scripts.

  $("#process-payment").click(function () {
            event.preventDefault();
            var form = $("#card-payment");
            $.validator.unobtrusive.parse(form);
            if (form.validate()) {
                console.log("valid");
                $.ajax({
                    url: '/payment/processcardpayment',
                    type: "POST",
                    data: form.serialize(),
                    success: function (data) {
                        console.log(data);

                    },
                    error: function (jqXhr, textStatus, errorThrown) {
                        alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
                    },
                    complete: function () {
                        //       $("#ProgressDialog").dialog("close");
                    }
                });
            } else {
                console.log("invalid");
            }

        });

1 Answer 1

2

You are calling event.preventDefault(); in your click handler but there's no event variable defined anywhere so I guess you get a javascipt error. Have you looked at the console of your javascript debugging tool by the way?

Maybe you meant your click handler to take this as argument:

$("#process-payment").click(function (evt) {
    evt.preventDefault();
    ...
});

But I'd actually recommend you subscribing to the submit event of the form instead of the click handler of a submit button. This will for example account for the case when the user presses Enter when inside some input field to submit the form instead of pressing on the submit button.

Also the correct method to verify if a form is valid is form.valid() and not form.validate() as in your example, In addition to that you don't need to call $.validator.unobtrusive.parse unless you are updating the DOM with a new form in say for example an AJAX call. In this case you should call this inside the success callback once you have replaced the DOM with the new form elements in order to parse the new unobtrusive validation rules.

So:

$('#card-payment').submit(function(evt) {
    evt.preventDefault();
    var form = $(this);
    if (form.valid()) {
        $.ajax({
            url: this.action,
            type: this.method,
            data: form.serialize(),
            success: function (result) {
                console.log(result);
            },
            error: function (jqXhr, textStatus, errorThrown) {
                alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
            },
            complete: function () {
                // $("#ProgressDialog").dialog("close");
            }
        });
    } else {
        console.log("invalid");
    }
});
Sign up to request clarification or add additional context in comments.

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.