Add Simple Validation to Your Search Bar with Bootstrap


Search bars are often overlooked when it comes to validation. Learn how to prevent empty search queries using Bootstrap validators.

Add Simple Validation to Your Search Bar with Bootstrap

You've probably heard the phrase form follows function. But when it comes to website forms, it can be more like dysfunction if you don't think about security. Forms are one of the easiest targets for spammers and bots – and that's why most web forms have some sort of validation in place.

With search bars (a form of a form, if you will), validation serves another purpose around usability. For example, depending on how a website is configured, when a user submits an empty query through a search box, all of your posts might show up.

Yikes. That could get confusing... and sort of defeats the purpose of a search bar simplifying your search.

One of the best ways to handle an empty search query from being submitted is to display a simple warning. In this tutorial, we'll show you how to customize your own warning to help prevent an empty search query, and we'll do it all with Bootstrap's handy validators.

Getting Started

Since we're using Bootstrap, go ahead and copy and paste the links below in the head section of your project's HTML file:

HTML

The HTML code below is an example of a hero section with a search box in the middle. The important parts to remember here are the role="form" and  data-toggle="validator" attributes in the form tag.

In addition, the search input field should have a "required" attribute. The required Boolean attribute is an HTML attribute that, if present, the user must specify a value for the input before the form can be submitted.

The data-error attribute specifies an error message such as "Please enter a search term." If the search is left blank, the help-block with-errors div specifies where the error message will be shown – in this case, right below the search box.

CSS

The CSS code sets the layout, positioning, and the style of elements. Feel free to change the color values and font styles to match your own website:

Javascript

The validation itself doesn't require any additional custom Javascript code.

The Javascript below is an optional code that activates the clear button when a letter or word is typed in the search box. By clicking on the "x" button that shows up, the user can easily clear the search box. You can either put this code inside the script tags in your project's HTML file or right-click to download the search.js file below:

search.js

And there you have it! Check out the JSFiddle below and try to click the search button without entering a search query to see the result:

Author

Sign up to explore

Create an account in seconds and start building today.

Sign up for Solodev

We use cookies to provide and improve our services. By using our site, you consent to cookies.