最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Add an error in ValidationSummary programmatically in data-ajax-success call - Stack Overflow

matteradmin4PV0评论

I'm displaying, with success, a ValidationSummary containing the errors that the jQuery unobstrusive validator detects :

<form asp-controller="PlanningYearsEditModal" asp-action="EditPlanningYear" data-ajax="true" data-ajax-method="POST" data-ajax-success="onSuccess">
    <div id="content" class="modal-body">
        @Html.ValidationSummary(false, null, new { @class = "text-danger" })
        <table class="inner" style="width:100%" border=1>
            <tr class="azurbox rounded3 white bold">
                <td style="width:20%">@CommonResources.CommonField</td>
                <td style="width:80%">@CommonResources.CommonValue</td>
            </tr>
            <tr class="underline">
                <td>@Html.LabelFor(model => model.LabelFr)</td>
                <td>
                    @Html.EditorFor(model => model.LabelFr)
                    @Html.ValidationMessageFor(model => model.LabelFr, "*", new { @class = "text-danger" })
                </td>
            </tr>
            <tr class="underline">
                <td>@Html.LabelFor(model => model.LabelNl)</td>
                <td>
                    @Html.EditorFor(model => model.LabelNl)
                    @Html.ValidationMessageFor(model => model.LabelNl, "*", new { @class = "text-danger" })
                </td>
            </tr>
        </table>
    </div>
    <div class="modal-footer">
        @Html.HiddenFor(model => model.Id)
        <button type="button" class="btn" data-dismiss="modal">Close</button>
        <button type="submit" class="btn">Save changes</button>
        <div id="Results"></div>
    </div>
</form>

After these simple checks, I have to do manual integrity checks in my controller, who returns a JSON containing the errors. I would like to use the validator to be able to display these errors in the ValidationSummary. I could probably update the html code with jQuery manually, but it causes a lot of issues (sometimes the validation summary already exists, sometimes not, sometimes you just have to replace a few bullets, sometimes not, ...).

I feel like there is probably a way to do this in a clean way.

I tried something like this, but it doesn't display anything on screen (and I can confirm that is code is being called) :

var onSuccess = function (errors) {
    var errorArray = {};
    errorArray["LabelFr"] = 'Some error thrown by the controller';
    $('#myForm').validate().showErrors(errorArray);
};

What can I do ?

I'm displaying, with success, a ValidationSummary containing the errors that the jQuery unobstrusive validator detects :

<form asp-controller="PlanningYearsEditModal" asp-action="EditPlanningYear" data-ajax="true" data-ajax-method="POST" data-ajax-success="onSuccess">
    <div id="content" class="modal-body">
        @Html.ValidationSummary(false, null, new { @class = "text-danger" })
        <table class="inner" style="width:100%" border=1>
            <tr class="azurbox rounded3 white bold">
                <td style="width:20%">@CommonResources.CommonField</td>
                <td style="width:80%">@CommonResources.CommonValue</td>
            </tr>
            <tr class="underline">
                <td>@Html.LabelFor(model => model.LabelFr)</td>
                <td>
                    @Html.EditorFor(model => model.LabelFr)
                    @Html.ValidationMessageFor(model => model.LabelFr, "*", new { @class = "text-danger" })
                </td>
            </tr>
            <tr class="underline">
                <td>@Html.LabelFor(model => model.LabelNl)</td>
                <td>
                    @Html.EditorFor(model => model.LabelNl)
                    @Html.ValidationMessageFor(model => model.LabelNl, "*", new { @class = "text-danger" })
                </td>
            </tr>
        </table>
    </div>
    <div class="modal-footer">
        @Html.HiddenFor(model => model.Id)
        <button type="button" class="btn" data-dismiss="modal">Close</button>
        <button type="submit" class="btn">Save changes</button>
        <div id="Results"></div>
    </div>
</form>

After these simple checks, I have to do manual integrity checks in my controller, who returns a JSON containing the errors. I would like to use the validator to be able to display these errors in the ValidationSummary. I could probably update the html code with jQuery manually, but it causes a lot of issues (sometimes the validation summary already exists, sometimes not, sometimes you just have to replace a few bullets, sometimes not, ...).

I feel like there is probably a way to do this in a clean way.

I tried something like this, but it doesn't display anything on screen (and I can confirm that is code is being called) :

var onSuccess = function (errors) {
    var errorArray = {};
    errorArray["LabelFr"] = 'Some error thrown by the controller';
    $('#myForm').validate().showErrors(errorArray);
};

What can I do ?

Share Improve this question edited Mar 27, 2018 at 11:13 Maistrenko Vitalii 1,0121 gold badge10 silver badges16 bronze badges asked Mar 27, 2018 at 9:34 IKIKN2IKIKN2 1453 silver badges12 bronze badges 8
  • Not sure why you think adding the <li> elements for you additional errors is an issue (and the <div> and <ul> elements generated by @Html.ValidationSummary() always exist) – user3559349 Commented Mar 27, 2018 at 9:40
  • I don't think so, when there are no errors, there is a div whose class is validation-summary-valid text-danger, and that is then replaced by a class named -danger validation-summary-errors where there is an error that the jquery unobstrusive validatiob detects. – IKIKN2 Commented Mar 27, 2018 at 9:47
  • If you return errors, you get the element using $('[data-valmsg-summary]'), set the class to "validation-summary-errors" and simply .append() the messages in a <li> - just a few lines of code – user3559349 Commented Mar 27, 2018 at 9:52
  • 1 var vs = $('[data-valmsg-summary]'); $.each(errorArray, function(index, item) { vs.children('ul').append($('<li></li>').text(item)); }); if (errorArray.length > 0) {vs.addClass('validation-summary-errors').removeClass('validation-summary-valid');} – user3559349 Commented Mar 27, 2018 at 9:57
  • 1 Use something like .append($('<li class="custom"></li>') in the code above, so that way you can remove any that you added previously (I assume that is what your mean) – user3559349 Commented Mar 27, 2018 at 10:11
 |  Show 3 more ments

1 Answer 1

Reset to default 6

When you use mvc's client side validatiion, the jquery.validate.unobtrusive.js plug-in parses the document and configures the $.validator in jquery.validate.js. You should not attempt to modify the $.validator or call validate().

Your @Html.ValidationSummary() generates a <div> (with a [data-valmsg-summary] attribute) which contains a <ul> element. To add the messages, you can simply add <li> elements containing the error message

var vs = $('[data-valmsg-summary]'); // get the div
if (errorArray.length > 0) {
    // update class name
    vs.addClass('validation-summary-errors').removeClass('validation-summary-valid');
}
$.each(errorArray, function(index, item) {
    // add each error
    vs.children('ul').append($('<li></li>').text(item));
});

If this is being called multiple times, and you do not want to display previously added errors, you can give the <li> elements a class name, say

vs.children('ul').append($('<li class="myerror"></li>').text(item));

and then remove them using vs.find('.myerror').remove();

Post a comment

comment list (0)

  1. No comments so far