Themeforest

Using jQuery to Validate Search Box Input

Today’s tip is just another simple example of how you can use the versatile jQuery library to validate form input text in your website.

In a recent project a client required validation on a search form input that would only allow numbers, letters and a “-”.

The Search Form

<form method="post" name="form1" action="">
     <fieldset>
          <div><label>Search:</label><input type="text" name="search-text" id="search-text" value="" size="32" /></div>
          <div><label></label><input type="submit" value="Submit" id="btn-search" /></div>
     </fieldset>
</form>

The jQuery Validation Code

jQuery(function(){
        $("#btn-search").click(function(){
        $(".error").hide();
        var hasError = false;
        var searchReg = /^[a-zA-Z0-9-]+$/;
        var searchVal = $("#search-text").val();
        if(searchVal == '') {
            $("#search-text").after('<span class="error">Please enter a search term.</span>');
            hasError = true;
        } else if(!searchReg.test(searchVal)) {
            $("#search-text").after('<span class="error">Enter valid text.</span>');
            hasError = true;
        }
        if(hasError == true) {return false;}
    });
});

The above code will first check that text has been entered and return an error message if the search box is empty. Then check, using a simple regular expression, that the entered text only contains alphanumeric characters or a “-”. If either of these validation checks return and error message then the form submission is stopped with the “return false” command.

Check out the demo.

Leave a comment

To add code to your comments wrap the code text in [text][/text] tags