mardi 5 mai 2015

Datatables Custom Wildcard Search

I am trying to perform a custom search using datatables. I am having trouble searching with a wildcard.

The data in the column has a specific format.

AB
AB[A-Z]
AB[A-Z]-00[0-9]

I only want to return a result if the format matches or there is a wildcard. So,

if the input is "AB" don't return ABC or ABC-00X
if the input is "ABC" don't return AB or ABC-00X
if the input is "ABC-00X" only return ABC-00X
if the input is "ABC*" return ABC-001, ABC-002, ABC-003, and so on...

I am intercepting the input field using:

    $(".dataTables_filter input")
        .off()
        .on('input', function (e) {
            var search = this.value;

            if (search.length >= 2 ) {
            var newSearch;
            if (/^(AB)$/i.test(search)) {
                newSearch = '^AB$';
            } else
                if (/^(AB[A-Z]-00[0-9])/i.test(search)) {
                    newSearch = search;
                } 
            else
                if (/^(AB[A-Z])/i.test(search)) {
                    newSearch = '^' + search.split('-')[0] + '$';
                } 

                oTable.fnFilter(newSearch, 4, true, false, false, true);
            }
            if (this.value.length < 2) {
                oTable.fnFilter('', 4, false, false, false, true)
            }
            return;
        });

I am using a regex search to check the input and make sure it matches the right format, then creating an new regex string to search. I run into a problem when trying to use a wildcard. I suspect the first regex layer is testing if an actual asterisk exists and it doesn't. I'm just not sure how to pass the asterisk through to the second layer.

Aucun commentaire:

Enregistrer un commentaire