Code for validating search box and button using jquery - Magesan

Code for validating search box and button using jquery

Code for validating search box and button using jquery

jQuery(this).ready(function() {
	jQuery("#btn-search").click(function() {
		jQuery(".error").hide();
		var hasError  = false;
		var searchReg = /^[a-zA-Z0-9-]+$/;
		var searchVal = jQuery("#search-field").val();
		if(searchVal == '') {


			jQuery("#search-field").after('<span class="error">Please enter a search term.</span>');
			hasError = true;
		} else if(!searchReg.test(searchVal)) {
			jQuery("#search-field").after('<span class="error">Enter valid text.</span>');
			hasError = true;


		}
		if(hasError == true) {return false;}
	});
});

Note :- #btn-search could be your submit button and the #seach-field could be your search box bar.

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>