bmurrell30
bmurrell30

Reputation: 715

SweetAlert2 allows an ASP.NET Core MVC form to post with missing required data. How to fix this?

I have an ASP.NET Core MVC application with a large form, including many required fields. If the user tries to submit the form with missing required information, I want to include an alert message as part of the feedback, and to keep the design simple I'm trying to incorporate said feedback into the jquery.validate process.

After playing around with the jquery.validate code, I have determined the place to set off my notifications is at the end of the onErrors function in jquery.validate.unobtrusive.js, found at line 69 in my copy of the library:

function onErrors(event, validator) {  // 'this' is the form element
    var container = $(this).find("[data-valmsg-summary=true]"),
        list = container.find("ul");

    if (list && list.length && validator.errorList.length) {
        list.empty();
        container.addClass("validation-summary-errors").removeClass("validation-summary-valid");

        $.each(validator.errorList, function () {
            $("<li />").html(this.message).appendTo(list);
        });

        // <-- MY CODE GOES HERE 
    }
}

If I use a standard alert message here, I get the expected behavior: the message shows, the user acknowledges, and the validator marks the missing required fields. But if I use a SweetAlert2 message, the submit process is allowed to go straight through to the post every time.

Here's an example of how I'm firing my SweetAlert message:

Swal.fire({
    title: 'Required Input Missing',
    html: 'One or more required fields have been left blank.',
    icon: 'error',
    allowOutsideClick: false,
    allowEscapeKey: false,
    allowEnterKey: false
});

It doesn't matter if I fire this message directly within the onErrors function, or within its own function elsewhere. Any suggestions on what's going on?

Upvotes: 0

Views: 237

Answers (0)

Related Questions