Search bars are often overlooked when it comes to validation. Learn how to prevent empty search queries using Bootstrap validators.
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.
Since we're using Bootstrap, go ahead and copy and paste the links below in the head section of your project's HTML file:
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
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.
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.
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:
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: