Question

I have the following:

HTML

<form class="form-horizontal" role="form" id="Validation" method="post" action="form.php">

    <input class="form-control" type="text" name="hn" id="hostname" data-validation-regex-message="Please enter a valid hostname" data-validation-regex-regex="^((\*\.([a-zA-Z0-9]+-)*[a-zA-Z0-9]+\.)|(([a-zA-Z0-9]+-)*[a-zA-Z0-9]+\.)+)[A-Za-z]([A-Za-z0-9-]*[A-Za-z0-9])?$" required>

    <input id="submit" class="btn btn-info" type="submit" name="submit" value="Submit" />
    <input class="btn btn-default" type="reset" value="Clear" />

</form>

JS/Jquery

 $(document).ready(function(){
    if ($('input[type=text]').jqBootstrapValidation('hasErrors')) {
            $('.btn').attr('disabled', true);
        }
        else
        $('.btn').attr('disabled', false);
});

Using jqBootstrapValidation, I'm attempting to disable the submit button if the text input field contains an invalid hostname format.

But it doesn't seem to work. Can anyone point out why or/and what I'm doing wrong?

UPDATE: Found a way to disable the submit function (not the button):

Looking at the SubmitError callback (http://reactiveraven.github.io/jqBootstrapValidation/#configuration_options_submiterror).

This prevents the form from being submitted if the input field is invalid:

$('#hostname').jqBootstrapValidation(
    {
        submitFail: function ($form, errors) { 
            $('input[type=submit]').attr('disabled','disabled');
        }, 
        submitSuccess: function ($form, errors) { 
            $('input[type=submit]').removeAttr('disabled');
        }
    }
);

But it still doesn't actually disable the submit button itself.

No correct solution

OTHER TIPS

I created a fiddle including all the required JS/CSS, etc. but could not even get the simple example that jqBootstrapValidation provided to work with Bootstrap 3. After seeing the github repo, it appears that the plugin has not been updated in nearly a year. I recommend switching over to the jQuery Validation Plugin.

To use the jQuery Validation Plugin with Bootstrap, simply add this before your code to fix the formatting:

// override jquery validate plugin defaults
$.validator.setDefaults({
    highlight: function(element) {
        $(element).closest('.form-group').addClass('has-error');
    },
    unhighlight: function(element) {
        $(element).closest('.form-group').removeClass('has-error');
    },
    errorElement: 'span',
    errorClass: 'help-block',
    errorPlacement: function(error, element) {
        if(element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }
    }
});

Then, you can check the forms validity via the .valid() method. You probably want to test while the user is typing, in that case, use jQuery's .keyup() method in combination with .valid().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top