2012-08-08 78 views
2

我想驗證在自動完成框中輸入的特殊字符,例如!@#$%^ & *(),並可能給出警告框消息爲「請輸入有效的名稱」 。以下是我的片段:JQuery自動完成Ajax驗證特殊字符

$("#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); 
} 

任何幫助將不勝感激。

在此先感謝

回答

1

在文本框內看到上blocking special characters這個問題。

您可以在發送請求之前設置驗證。相反,建立一個整體的驗證插件,它做一切對keypress

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

OR

的您可以通過發送stripping out special characters,而不是阻止該請求。 (用戶更加友好)

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

粘貼相關的代碼以供參考