How to use jQuery validation to set the search bar to accept only a specific input?

I’m new to the wordpress world. As a starter theme I was suggested to use the basic one given by underscores.me. The search bar is fundamental for my site, so I would like to customize it in order to accept only a specific input from users.

In particular, the only accepted input have to be of the form xay where x and y are numbers between 1 and 999, and a has to be the letter a.

Examples of accepted input: 1a2, 222a999, 130a28.

I read articles How do I add a simple jQuery script to WordPress?
and How to Properly Add jQuery Scripts to WordPress on how to properly add a jQuery script in wordpress, but it doesn’t work.

This is what I did so far:

Since the theme doesn’t have the searchform.php file, I’m using the default search bar. In the folder wp-contentthemesmythemejs I created the file searchbox.js and in it I wrote the following code

jQuery(function(){
$(“#btn-search”).click(function(){
$(“.error”).hide();
var hasError = false;
var searchReg = /^[0-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;}
});
});

I found this code here, it will first check that text has been entered and return an error message if the search box is empty. Then it checks that the entered text only contains numeric characters. If either of these validation checks return an error message, then the form submission is stopped with the “return false” command.

This is not exactly what I’d like to have for my search bar, I used it just to try how to add a jQuery script.

Then in the functions.php file I wrote, at the top, this code

function add_my_script() {
wp_enqueue_script(
‘searchbox’, // name your script so that you can attach other scripts and de-register, etc.
get_template_directory_uri() . ‘/js/searchbox.js’, // this is the location of your script file
array(‘jquery’) // this array lists the scripts upon which your script depends
);
}
add_action( ‘wp_enqueue_scripts’, ‘add_my_script’ );

Then I tried to do a search on my site, I wrote nothing in the search box and clicked the search button. No error message appeared, and all the posts on the site where shown. Moreover, I wrote in the search box a word (which would not be possibile to search for since the command var searchReg = /^[0-9]+$/; should only accept numeric input, but again no error messages and pages where shown.

What I did wrong?

Read more here:: How to use jQuery validation to set the search bar to accept only a specific input?

Leave a Reply

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