javascriptvalidationformswebshim

Webshim form validation: How to add custom validation for button?


I have a input type of button in form, along with a hidden input field type of text. Can webshim customize validation, so that it can validation whether the btn has been clicked by checking if the hidden field has value( my button will pass value to hidden value onclick), and apply the validation error class to btn?


Solution

  • Submitters and inputs in hidden state are always barred from validation. Therefore you can't do it this way. But you can do something else:

    Use an input with state checkbox and style its label like it would be a normal button. Then you add a change listener and as soon as it was checked, prevent any further changes. This way it can't be unchecked anymore and the value of the checkbox will be sent to the server.

    Here is a simple demo: http://jsfiddle.net/trixta/8fpZ3/

    And this is how the JS looks to make it only one time clickable:

       $(function () {
            $('.btn-checkbox input').each(function () {
                var onCheck = function () {
                    if(elem.prop('checked')){
                        elem.off('change', onCheck);
                        elem.on('click', false);
                    }
                };
                var elem = $(this).on('change', onCheck);
            });
        });