Bootstrap form validation changing success and error colors

10,688

Solution 1

There is a CSS selector for this purpose (:invalid), but on the individual input level. You can color the whole form by checking for children which are invalid, like so:

/* add space to denote child element */
form :invalid {
    background: red;
}

Solution 2

For Bootstrap, just add has-error class to form group.

<div class="form-group has-error">
  <label class="col-md-4 control-label" for="name">Name</label>  
  <div class="col-md-5">
  <input id="name" name="name" type="text" placeholder="Enter Name" class="form-control input-md" required="">
  </div>
</div>

For more information, look the documentation: http://getbootstrap.com/css/#forms-help-text

And live demo: http://jsbin.com/daxocivoho/1/edit?html,output

Share:
10,688
Ralph Macalino
Author by

Ralph Macalino

I am a college student i spend most of my time at school. By night i play games/ do codes.

Updated on July 21, 2022

Comments

  • Ralph Macalino
    Ralph Macalino almost 2 years

    This is my form, i want the form to change colors when errors/something occurs.

    Example, if a user did not input anything in a required field,
    i want it to change colors using bootstrap's css classes, can anyone teach me how i could make that happen?
    p.s. i am new, so sorry for a newbie question.

    <form class="form-horizontal">
    <fieldset>
    
    <!-- Form Name -->
    <legend>Form Name</legend>
    
    <!-- Text input-->
    <div class="form-group">
      <label class="col-md-4 control-label" for="name">Name</label>  
      <div class="col-md-5">
      <input id="name" name="name" type="text" placeholder="Enter Name" class="form-control input-md" required="">
    
      </div>
    </div>
    
    <!-- Password input-->
    <div class="form-group">
      <label class="col-md-4 control-label" for="password">Password</label>
      <div class="col-md-5">
        <input id="password" name="password" type="password" placeholder="Enter Password" class="form-control input-md" required="">
    
      </div>
    </div>
    
    <!-- Button -->
    <div class="form-group">
      <label class="col-md-4 control-label" for="button"></label>
      <div class="col-md-4">
        <input type = "submit" id="button" name="button" value = "Submit" class="btn btn-success">
      </div>
    </div>
    
    </fieldset>
    </form>