Required form field in Bootstrap
Required form field in Bootstrap : It is very simple and easy to make form field required. You can make form field required by just adding a simple function which will add the bootstrap’s predefined class to show input field error. Here in this tutorial we are going to explain how you can make form input as required entry. You can use our online editor to edit the code online and see output.
How to make Required form field in Bootstrap
Here we have created a simple function which is triggered on the keyup event of form field email which adds the has-error class to the parent div and removes the class when email field has some value.-
Required form field in Bootstrap Example :
<html> <head> <title>Bootstrap Form Required Field</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script> <script type='text/javascript'> function validate(el){ if($(el).val() == ''){ $(el).parent('div').addClass('has-error'); }else{ $(el).parent('div').removeClass('has-error'); } } </script> </head> <body> <div class="container"> <div class="row" style="margin:50px;"> <div class="col-sm-12"> <form role="form"> <div class="form-group has-error"> <label for="email">Email</label> <input type="text" name="email" class="form-control" onkeyup='validate(this);' id="email" placeholder="Enter email"> </div> </form> </div> </div> </div> </body> </html> |
If you run the above example it will produce the output something like this –
Advertisements