admin管理员组

文章数量:1026989

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();

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();

本文标签: javascriptAdd an error in ValidationSummary programmatically in dataajaxsuccess callStack Overflow