Enabling disabled button after successful jQuery validation

后端 未结 2 1230
星月不相逢
星月不相逢 2020-12-28 10:27

I have the following code where I have 2 email input fields which I need to validate they are the same which is working successfully using jQuery validate equalTo.



        
2条回答
  •  感情败类
    2020-12-28 11:26

    There is no jQuery Validate plugin callback option/function that fires when all fields are valid without first clicking the submit button.

    You'll need to create an external keyup blur event handler that checks your form for validity and enables/disables the button accordingly; every time a key is pressed or you leave a field.

    DEMO: http://jsfiddle.net/p628Y/1/

    $(document).ready(function () {
    
        $('#ccSelectForm').validate({
            rules: {
                inputEmail: {
                    required: true,
                    email: true
                },
                inputEmailConfirm: {
                    // required: true,  // <-- redundant
                    // email: true,     // <-- redundant
                    equalTo: '#inputEmail'
                }  // <-- removed trailing comma
            }
        });
    
        $('#ccSelectForm input').on('keyup blur', function () { // fires on every keyup & blur
            if ($('#ccSelectForm').valid()) {                   // checks form for validity
                $('button.btn').prop('disabled', false);        // enables button
            } else {
                $('button.btn').prop('disabled', 'disabled');   // disables button
            }
        });
    
    });    
    

    Since the jQuery Validate plugin disables the browser's HTML5 validation dynamically, I removed the required attribute from your markup and changed type="email" into type="text". (You already have these validation rules specified in the plugin.)

    
    
    

    You also don't need to specify all the rules twice when using the equalTo rule as the second field must already always match the first.


    EDIT:

    In the above scenario, your page is totally dependent upon JavaScript. In other words, without JavaScript, the button is always disabled.

    If you have server-side validation in place and want your page to be independent of JavaScript, you'll need to remove the disabled="disabled" from your button markup and add it to your JavaScript just inside the DOM ready event handler.

    $('button.btn').prop('disabled', 'disabled');
    

    In this scenario, without JavaScript, you'll still have a working button, and with JavaScript, the button is disabled programatically on page load.

提交回复
热议问题