ryanelian / aspnet-validation

Enables ASP.NET MVC client-side validation without jQuery!
MIT License
40 stars 13 forks source link

Ignores formaction attibute on submit button #7

Open mechanic22 opened 5 years ago

mechanic22 commented 5 years ago

It seems this library ignores the formaction attribute if on a submit button

With your aspnet-validation enabled, no matter which button you click it posts to the /manage endoint instead of the /manage-differently endpoint specified by the button's formaction attribute no matter which button you click,

<form method="POST" action="/manage">
    <button type="submit">Submit Actual Form</button>
    <button type="submit" formaction="/manage-differently">Submit To Separate Endpoint</button>
</form>
mechanic22 commented 5 years ago

I got around the issue by adding this javascript to document load before calling your initialization. Though not sure if this is something that could/should be pulled into the library. NOTE: The click event must occur before the submit event occurs of the form

Though I havent done much testing, especially if multiple forms occur however I figured I'd share

   <script type="text/javascript">
        var forms = document.getElementsByTagName('form');

        for (var i = 0; i < forms.length; i++) {

            (function (form) {
                var defaultAction = form.action;
                var buttons = form.querySelectorAll("button[type=submit],input[type=submit]");
                var containsFormActionButton = false;

                for (var j = 0; !containsFormActionButton && j < buttons.length; j++) {
                    var button = buttons.item(j);
                    containsFormActionButton = button.hasAttribute('formaction');
                }

                if (containsFormActionButton) {
                    for (var k = 0; k < buttons.length; k++) {
                        buttons.item(k).addEventListener('click', (e) => {
                            form.action = e.target.hasAttribute('formaction') ? e.target.getAttribute('formaction') : defaultAction;
                        });
                    }
                }
            })(forms.item(i));
        }
    </script>
ryanelian commented 5 years ago

Hello, thank you for the bug report.

I will look into this with the other guy's issue when I have time. Currently on a very critical, high priority IRL project.

ridercz commented 5 years ago

I can confirm both the problem and workaround.