6

I want to validate a form in a bootstrap modal without using any framework. It's actually a simple modal with only an input text and two buttons "Close" and "Send". The user should type his/her name in the input box and click send. The form is the sent with the method post.

What I want to do is that, if the user doesn't enter anything in the input box of and clicks on the button "Send", the input box should have a red border circling it instead of the default blue border. Here's the code for my modal:

<div id="myModal" class="modal fade" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <!--form-->

            <form class = "form-horizontal" id="myForm" method="post" action="test.php" role="form">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title">My modal</h4>
                </div>
                <div class="modal-body">
                    <p>
                        Please enter your name:
                    </p>
                    <br/>

                    <div class="form-group">

                        <div class="col-lg-12">
                            <label class="control-label" for="firstname">Name</label>
                            <input type="text" class="form-control required" id="firstname" name="firstname">
                        </div>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button id="myFormSubmit" class="btn btn-primary">Send</button>
                </div>
            </form>
        </div>
    </div>
</div>

I tried using javascript to change the class of the input text to has-errorbut it doesn't produce the red outline. When I click on send it sends the empty value through the post method instead of Here's my javascript code:

    <script type="text/javascript">
        $('#myForm').validate({
            rules: {
                name: {
                    minlength: 1,
                    required: true
                },
            },
            highlight: function (element) {
                $('#firstname').removeClass('has-success').addClass('has-error');
            },
            success: function (element) {
                $('#firstname').removeClass('has-error').addClass('has-success');
            }
        });
    </script>

I feel like I'm mixing a whole lot of things here. I'm still new to bootstrap and javascript. How can I go about getting the desired red outline? Thanks.

Edit: Validate function:

function validate() {
    var x = document.forms["myForm"]["firstname"].value;
    if (x == null || x == "") {
        return false;
    }
}

4 Answers 4

12

You need to change the CSS classes of the input parent element div.form-group, not the input itself:

The HTML after the submit button click should look like this:

<div class="form-group has-error">
   <div class="col-lg-12">
      <label class="control-label" for="firstname">Name</label>
      <input type="text" class="form-control required" id="firstname" name="firstname">
    </div>
</div>

To achieve this, alter your JavaScript code to this:

<script type="text/javascript">
  $('#myForm').on('submit', function(e) {
    var firstName = $('#firstname');

    // Check if there is an entered value
    if(!firstName.val()) {
      // Add errors highlight
      firstName.closest('.form-group').removeClass('has-success').addClass('has-error');

      // Stop submission of the form
      e.preventDefault();
    } else {
      // Remove the errors highlight
      firstName.closest('.form-group').removeClass('has-error').addClass('has-success');
    }
  });
</script>
8
  • Thanks for your help. I understood a thing or two. I tried your code but the input is outlined red from the start. I think I didn't express myself well. I want the input to be outlined red only after clicking on the send button. If the input is empty and the user clicks on the send button, then it should outline the input red.
    – mkab
    Jan 15, 2015 at 17:01
  • I see, I put the HTML code just to show you where in the DOM should the has-error CSS class stand. You need only the JavaScript not the HTML. The initial state of should not have the has-error class. Jan 15, 2015 at 17:06
  • Oh ok I see. Still the form is submitted even if the input text is empty. Perhaps I should prevent the default action of the form, because the form is using a post method. How can I go about this?
    – mkab
    Jan 15, 2015 at 17:09
  • I thought you have problems highlight the errors, not the validation itself. To help with the validation I need the code for this .validate() function that you are applying to the form. Jan 15, 2015 at 17:12
  • 1
    Unbelievable! After minutes of debugging, I found out that why it wasn't working was because I had the <script src="http://code.jquery.com/jquery.min.js"></script> just below the javascript code your wrote. I guess it should be called before. But I thought that when the pages load all the javascript codes execute irrespective of where you place them. I guess I was wrong. At least I would never forget my error. Thanks! :)
    – mkab
    Jan 15, 2015 at 18:01
1

div in boot strap...

<div class="form-group">
    <div class="row">

        <label class="col-xs-2 col-sm-2 control-label">city:</label>

        <div class="col-xs-3 col-sm-3 formGroups"
            id="city_form1">
            <form:input name="city" class="form-control"
                placeholder="City" data-toggle="tooltip"
                data-placement="bottom" title="City" maxlength="15" />

            <small class="help-block col-sm-offset-0 col-sm-9"
                style="display: none;">city must require</small>
        </div>
    </div>
</div>

as you see there is .help-block is display: none now you write javascript function and check validation and if validation now pass make it display: block ... that's way you can do

enjoy with boot strap :)

1
  • Thanks for your help. I want to outline the input text red not display a message saying that a certain input is required. Though I agree this is one way of validating the form
    – mkab
    Jan 15, 2015 at 17:12
1

its very easy

just apply class .has-error to div by javascript function

<div class="form-group has-error">
    <div class="row">

        <label class="col-xs-2 col-sm-2 control-label">city:</label>

        <div class="col-xs-3 col-sm-3 formGroups"
            id="city_form1">
            <form:input name="city" class="form-control"
                placeholder="City" data-toggle="tooltip"
                data-placement="bottom" title="City" maxlength="15" />

        </div>
    </div>
</div>
0

Just use required inside the input field like this

<input type="text" class="form-control required" id="firstname" name="firstname" required/>
2
  • This is very risky. HTML5 validations can be bypassed very easily.
    – Hanmaslah
    Nov 18, 2016 at 6:52
  • 3
    @Hanmaslah any client-side validation can be bypassed easily, so you should almost always also use server-side validation
    – Cocowalla
    Oct 31, 2017 at 21:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.