thameem ansari
thameem ansari

Reputation: 21

JQuery Auto-complete Ajax validate special characters

i want to validate the special characters like !@#$%^&*() entered in the auto complete box and possibly give an alert box message as "Please enter a valid name". Below is my snippet:

$("#txtName").autocomplete({
    source: function (request, response) {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Webservice.asmx/GetNames",
            data: "{'prefixText':'" + request.term + "'}",
            dataType: "json",
            success: function (data) {
                response($.map(data.d, function (item) {
                    return {
                        label: item.split('|')[0],
                        val: item.split('|')[1]
                    }
                }))
            },
            error: function (result) {
                ServiceFailed(result);
            },
            failure: function (response) {
                ServiceFailed(result);
            }
        });
    },
    select: function (event, ui) {
        autoName(ui.item.val, ui.item.label);
    },
    minLength: 4
}).data("autocomplete")._renderItem = function (ul, item) {
    var newText = String(item.value).replace(
            new RegExp(this.term, "gi"),
            "<span class='ui-state-highlight'>$&</span>");
    return $("<li></li>")
        .data("item.autocomplete", item)
        .append("<a>" + newText + "</a>")
        .appendTo(ul);
}

Any help would be much appreciated.

Thanks in advance

Upvotes: 2

Views: 1558

Answers (1)

Robin Maben
Robin Maben

Reputation: 23064

See this question on blocking special characters in a textbox.

You could probably set up the validation before sending the request. Instead of setting up a whole validation plugin, which does everything on keypress

$.ajax({  
    url : url, //blah blah
    beforeSend : function(){
      if(!validateChars()){
        return false;
      }
    }
});

OR

You could send the request by stripping out special characters instead of blocking. (more user friendly)

var alowedChars = stringToReplace.replace(/[^\w\s]/gi, '')

Pasted relevant code for reference

Upvotes: 1

Related Questions