Manually adding & removing validation errors to jQuery validator

前端 未结 3 1641
北恋
北恋 2021-02-02 06:46

I have a search form & knockout-based grid for results. When search is performed, there is some server-side validation taking place on asp.net mvc, and if model state is not

3条回答
  •  不知归路
    2021-02-02 07:47

    I have solved this by overriding showErrors function in jQuery validator with my own, which is compatible with unobtrusive-generated validation spans, and cleaning up valid fields which have invalid class. It is not very nice workaround but it works.

    Here is jsfiddle with solution: http://jsfiddle.net/goranobradovic/ughCm/5/

    UPDATE: As link to external site is not proper answer according to site guidelines, I'm adding code sample here. For anyone already familiar with jQuery validation, just look at two lines of code in showErrors function. I assigned it to validator with validator.settings.showErrors = showErrors;.

    HTML:




    Debug:

    JavaScript:

    var validator = {};
    
    function addError(e) {
        validator.showErrors({
            "FirstName": "test error"
        });
    }
    
    function removeError(e) {
        validator.showErrors({
            "FirstName": null
        });
        fixValidFieldStyles($("form"), validator);
    }
    
    $(document).ready(function() {
        var $form = $("#experiment");
        // prevent form submission
        $form.submit(function(e) {
            e.preventDefault();
            return false;
        });
        $("#add").click(addError);
        $("#remove").click(removeError);
        $("#debug").html("

    Validator properties:

    "); validator = $form.validate(); validator.settings.showErrors = showErrors; for (var i in validator) { var row = $("").html(i).append("
    "); $("#debug").append(row); } }); function showErrors(errorMessage, errormap, errorlist) { var val = this; errormap.forEach(function(error, index) { val.settings.highlight.call(val, error.element, val.settings.errorClass, val.settings.validClass); $(error.element).siblings("span.field-validation-valid, span.field-validation-error").html($("").html(error.message)).addClass("field-validation-error").removeClass("field-validation-valid").show(); }); } function fixValidFieldStyles($form, validator) { var errors = {}; $form.find("input,select").each(function(index) { var name = $(this).attr("name"); errors[name] = validator.errorsFor(name); }); validator.showErrors(errors); var invalidFields = $form.find("." + validator.settings.errorClass); if (invalidFields.length) { invalidFields.each(function(index, field) { if ($(field).valid()) { $(field).removeClass(validator.settings.errorClass); } }); } }

提交回复
热议问题