Jquery post and unobtrusive ajax validation not working mvc 4

You are calling your post via ajax so you will need to manually call $form.validate(); and test the result with $form.valid():

function SaveCity() {

    $.validator.unobtrusive.parse($form);
        $form.validate();
        if ($form.valid()) {

        $.ajax({
            type: "POST",
            url: "/Home/SaveCity",
            contentType:"application/json; charset=utf-8",
            data: {
            Id: $('.cityId').val(),
            City: $('.cityName').val()
            },
            success: function (data) {
            }

        });

    }
}

If it is purely client-side, the errors will be contained within the jquery validation object $form.validate().errorList but you will have to do some manual processing similar to what I mention below.

If you wish to return server-side model state you can add the model state errors as a key value pair in your controller and return them as json.

You can use the below method to display the messages.

This finds all the validation message spans with model state error keys and adds the red error message to them. Please note you may want to adapt this to display many error messages against a key.

public doValidation(e)
{
        if (e.data != null) {
            $.each(e.data, function (key, value) {
                $errorSpan = $("span[data-valmsg-for="" + key + ""]");
                $errorSpan.html("<span style="color:red">" + value + "</span>");
                $errorSpan.show();
            });
        }
}

Updated

Here is the above adapted so you can parse it manually from the jquery unobtrusive errors instead:

        $.each($form.validate().errorList, function (key, value) {
            $errorSpan = $("span[data-valmsg-for="" + value.element.id + ""]");
            $errorSpan.html("<span style="color:red">" + value.message + "</span>");
            $errorSpan.show();
        });

Just pop that in an else statement and you are good to go. 🙂

Leave a Comment