2009-05-21 54 views

回答

2

這是防止用戶refrence在這裏輸入字符 「a」

$(function() { 
$('input:text').keydown(function(e) { 
if(e.keyCode==65) 
    return false; 

}); 
}); 

鍵碼的例子:
http://www.expandinghead.net/keycode.html

+0

我認爲所有你不想允許的鍵碼都可以壓倒性地嘗試和管理。 – RSolberg 2009-05-21 23:14:09

+0

我不明白,怎麼了? – 2009-05-21 23:18:21

+0

如果您想限制某人只能輸入數字1到5,則最終管理代碼中的5個鍵碼。 – RSolberg 2009-05-21 23:19:33

9

看看jQuery的字母數字插件。 https://github.com/KevinSheedy/jquery.alphanum

//All of these are from their demo page 
//only numbers and alpha characters 
$('.sample1').alphanumeric(); 
//only numeric 
$('.sample4').numeric(); 
//only numeric and the . 
$('.sample5').numeric({allow:"."}); 
//all alphanumeric except the . 1 and a 
$('.sample6').alphanumeric({ichars:'.1a'}); 

您可以通過添加masked inputs一步藉此...

+14

現在這個鏈接被破壞了! – 2012-05-29 06:21:13

+4

斷開的鏈接.. :( – 2012-12-01 05:34:43

+1

TOP鏈接被打破 – thecoolmacdude 2015-06-16 20:51:41

1

是的,你可以通過使用jQuery因爲這樣做:

<script> 
$(document).ready(function() 
{ 
    $("#username").blur(function() 
    { 
     //remove all the class add the messagebox classes and start fading 
     $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow"); 
     //check the username exists or not from ajax 
     $.post("user_availability.php",{ user_name:$(this).val() } ,function(data) 
     { 
      if(data=='empty') // if username is empty 
      { 
      $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox 
      { 
       //add message and change the class of the box and start fading 
       $(this).html('Empty user id is not allowed').addClass('messageboxerror').fadeTo(900,1); 
      }); 
      } 
      else if(data=='invalid') // if special characters used in username 
      { 
      $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox 
      { 
       //add message and change the class of the box and start fading 
       $(this).html('Sorry, only letters (a-z), numbers (0-9), and periods (.) are allowed.').addClass('messageboxerror').fadeTo(900,1); 
      }); 
      } 
      else if(data=='no') // if username not avaiable 
      { 
      $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox 
      { 
       //add message and change the class of the box and start fading 
       $(this).html('User id already exists').addClass('messageboxerror').fadeTo(900,1); 
      });  
      } 
      else 
      { 
      $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox 
      { 
       //add message and change the class of the box and start fading 
       $(this).html('User id available to register').addClass('messageboxok').fadeTo(900,1); 
      }); 
      } 

     }); 

    }); 
}); 
</script> 
<input type="text" id="username" name="username"/><span id="msgbox" style="display:none"></span> 

和腳本爲您user_availability.php將是:

<?php 
include'includes/config.php'; 

//value got from the get method 
$user_name = trim($_POST['user_name']); 

if($user_name == ''){ 
    echo "empty"; 
}elseif(preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $user_name)){ 
    echo "invalid"; 
}else{ 
    $select = mysql_query("SELECT user_id FROM staff"); 

    $i=0; 
    //this varible contains the array of existing users 
    while($fetch = mysql_fetch_array($select)){ 
     $existing_users[$i] = $fetch['user_id']; 
     $i++; 
    } 

    //checking weather user exists or not in $existing_users array 
    if (in_array($user_name, $existing_users)) 
    { 
     //user name is not availble 
     echo "no"; 
    } 
    else 
    { 
     //user name is available 
     echo "yes"; 
    } 
} 
?> 

我試圖添加/\但未成功。


你也可以做到這一點通過使用JavaScript代碼&將是:

<!-- Check special characters in username start --> 
<script language="javascript" type="text/javascript"> 
function check(e) { 
    var keynum 
    var keychar 
    var numcheck 
    // For Internet Explorer 
    if (window.event) { 
     keynum = e.keyCode; 
    } 
    // For Netscape/Firefox/Opera 
    else if (e.which) { 
     keynum = e.which; 
    } 
    keychar = String.fromCharCode(keynum); 
    //List of special characters you want to restrict 
    if (keychar == "'" || keychar == "`" || keychar =="!" || keychar =="@" || keychar =="#" || keychar =="$" || keychar =="%" || keychar =="^" || keychar =="&" || keychar =="*" || keychar =="(" || keychar ==")" || keychar =="-" || keychar =="_" || keychar =="+" || keychar =="=" || keychar =="/" || keychar =="~" || keychar =="<" || keychar ==">" || keychar =="," || keychar ==";" || keychar ==":" || keychar =="|" || keychar =="?" || keychar =="{" || keychar =="}" || keychar =="[" || keychar =="]" || keychar =="¬" || keychar =="£" || keychar =='"' || keychar =="\\") { 
     return false; 
    } else { 
     return true; 
    } 
} 
</script> 
<!-- Check special characters in username end --> 

<!-- in your form --> 
    User id : <input type="text" id="txtname" name="txtname" onkeypress="return check(event)"/> 
+2

老兄,你已經包括了一大堆可能沒有幫助的多餘代碼。最低限度?他問的是jQuery,我不確定PHP是否相關。 – 2011-09-21 04:49:32

116

使用正則表達式,你可以改變,以允許/禁止任何你喜歡的一個簡單的例子。

$('input').on('keypress', function (event) { 
    var regex = new RegExp("^[a-zA-Z0-9]+$"); 
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode); 
    if (!regex.test(key)) { 
     event.preventDefault(); 
     return false; 
    } 
}); 
1

只是數字:

$( 'input.time')的keydown(函數(E){如果(e.keyCode> = 48 & & e.keyCode < = 57 ){ return true;} else { return false;}});

或時間,包括 「:」。

$( 'input.time')的keydown(函數(E){如果(e.keyCode> = 48 & & e.keyCode < = 58){ return true;} else { return false;}});

還包括刪除和退格:

$( 'input.time')的keydown(函數(E){如果((e.keyCode> = 46 & & e.keyCode < = 58)|| e。keyCode == 8){return true; } else { return false; }});

unfortuneatly沒有得到它在一臺iMac

工作
1

通緝亞歷克斯對戴爾的回答評論發表評論。不可能(首先需要多少「代表」?這不會很快發生..奇怪的系統) 因此作爲回答:

退格可以通過添加\ b添加到像這樣的正則表達式定義:[a- ZA-Z0-9 \ b]。 或者你乾脆讓整個拉美範圍,包括更多或更少的東西「非異國情調」的字符(也控制諸如退格字符):^ [\ u0000- \ u024F \ u20AC] + $

只有真正的unicode以外拉丁字符有歐元符號(20ac),添加任何你可能需要的東西。

同時還處理通過複製粘貼&輸入的輸入,簡單地也結合了「改變」事件,並檢查輸入有太多 - 刪除它或它條帶化/讓像「不支持的字符」錯誤消息..

if (!regex.test($j(this).val())) { 
    alert('your input contained not supported characters'); 
    $j(this).val(''); 
    return false; 
} 
38

我一直在尋找一個答案,只限於輸入字母數字字符,但仍然允許使用控制字符(例如,退格,刪除,製表符)和複製粘貼。沒有提供的答案,我嘗試滿足所有這些要求,所以我想出了以下使用input事件。

$('input').on('input', function() { 
    $(this).val($(this).val().replace(/[^a-z0-9]/gi, '')); 
}); 

編輯:
作爲rinogo在評論中指出,上面的代碼段中的輸入文本中間打字時光標強制輸入的結束。我相信下面的代碼片段解決了這個問題。

$('input').on('input', function() { 
    var c = this.selectionStart, 
     r = /[^a-z0-9]/gi, 
     v = $(this).val(); 
    if(r.test(v)) { 
    $(this).val(v.replace(r, '')); 
    c--; 
    } 
    this.setSelectionRange(c, c); 
}); 
43

簡短的回答:防止 '按鍵' 事件:

$("input").keypress(function(e){ 
    var charCode = !e.charCode ? e.which : e.charCode; 

    if(/* Test for special character */) 
     e.preventDefault(); 
}) 

龍答:使用像jquery.alphanum

有幾件事情采摘的解決方案時需要考慮的一個插件:

  • 粘貼文本
  • 上述代碼可能會阻止控制字符(如退格鍵或F5)。
  • E,I,ä等
  • 阿拉伯語或中國...
  • 跨瀏覽器兼容

我覺得這個面積足夠複雜的使用第三方插件來保證。我嘗試了幾個可用的插件,但發現它們每個都存在一些問題,所以我繼續寫下jquery.alphanum。代碼如下所示:

$("input").alphanum(); 

或瞭解更多細粒度的控制,增加一些設置:

$("#username").alphanum({ 
    allow  : "€$£", 
    disallow : "xyz", 
    allowUpper : false 
}); 

希望它能幫助。

3

在文本框的onkeypress事件上寫一些javascript代碼。 按規定允許在你的文本

function isNumberKeyWithStar(evt) { 
    var charCode = (evt.which) ? evt.which : event.keyCode 
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 42) 
     return false; 
    return true; 
} 
function isNumberKey(evt) { 
    var charCode = (evt.which) ? evt.which : event.keyCode 
    if (charCode > 31 && (charCode < 48 || charCode > 57)) 
     return false; 
    return true; 
} 
function isNumberKeyForAmount(evt) { 
    var charCode = (evt.which) ? evt.which : event.keyCode 
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46) 
     return false; 
    return true; 
} 

9

使用HTML5的模式輸入屬性限制字符!

<input type="text" pattern="^[a-zA-Z0-9]+$" /> 
7

使用正則表達式來允許/禁止任何操作。另外,對於比接受的答案稍微更健壯的版本,允許不具有與它們相關聯的鍵值的字符(退格,選項卡,箭頭鍵,刪除等)可以通過首先經過按鍵事件並且根據鍵碼而不是值檢查密鑰。

$('#input').bind('keydown', function (event) { 
     switch (event.keyCode) { 
      case 8: // Backspace 
      case 9: // Tab 
      case 13: // Enter 
      case 37: // Left 
      case 38: // Up 
      case 39: // Right 
      case 40: // Down 
      break; 
      default: 
      var regex = new RegExp("^[a-zA-Z0-9.,/ [email protected]()]+$"); 
      var key = event.key; 
      if (!regex.test(key)) { 
       event.preventDefault(); 
       return false; 
      } 
      break; 
     } 
}); 
1

限制按鍵上的特殊字符。下面是關鍵代碼的測試頁:http://www.asquare.net/javascript/tests/KeyCode.html

var specialChars = [62,33,36,64,35,37,94,38,42,40,41]; 

some_element.bind("keypress", function(event) { 
// prevent if in array 
    if($.inArray(event.which,specialChars) != -1) { 
     event.preventDefault(); 
    } 
}); 

在轉角,我需要一個合適的貨幣格式的文本框我。我的解決辦法:

var angularApp = angular.module('Application', []); 

... 

// new angular directive 
angularApp.directive('onlyNum', function() { 
    return function(scope, element, attrs) { 

     var specialChars = [62,33,36,64,35,37,94,38,42,40,41]; 

     // prevent these special characters 
     element.bind("keypress", function(event) { 
      if($.inArray(event.which,specialChars) != -1) { 
       prevent(scope, event, attrs) 
      } 
     }); 

     var allowableKeys = [8,9,37,39,46,48,49,50,51,52,53,54,55,56 
      ,57,96,97,98,99,100,101,102,103,104,105,110,190]; 

     element.bind("keydown", function(event) { 
      if($.inArray(event.which,allowableKeys) == -1) { 
       prevent(scope, event, attrs) 
      } 
     }); 
    }; 
}) 

// scope.$apply makes angular aware of your changes 
function prevent(scope, event, attrs) { 
    scope.$apply(function(){ 
     scope.$eval(attrs.onlyNum); 
     event.preventDefault(); 
    }); 
    event.preventDefault(); 
} 

在HTML添加指令

<input only-num type="text" maxlength="10" id="amount" placeholder="$XXXX.XX" 
    autocomplete="off" ng-model="vm.amount" ng-change="vm.updateRequest()"> 

,並在相應的角控制器我只允許有到只有1週期,將文本轉換爲數字,並添加「模糊四捨五入數「

... 

this.updateRequest = function() { 
    amount = $scope.amount; 
    if (amount != undefined) { 
     document.getElementById('spcf').onkeypress = function (e) { 
     // only allow one period in currency 
     if (e.keyCode === 46 && this.value.split('.').length === 2) { 
      return false; 
     } 
    } 
    // Remove "." When Last Character and round the number on blur 
    $("#amount").on("blur", function() { 
     if (this.value.charAt(this.value.length-1) == ".") { 
      this.value.replace(".",""); 
      $("#amount").val(this.value); 
     } 
     var num = parseFloat(this.value); 
     // check for 'NaN' if its safe continue 
     if (!isNaN(num)) { 
     var num = (Math.round(parseFloat(this.value) * 100)/100).toFixed(2); 
     $("#amount").val(num); 
     } 
    }); 
    this.data.amountRequested = Math.round(parseFloat(amount) * 100)/100; 
} 

... 
0

要替換的特殊字符,空間和轉換爲小寫

$(document).ready(function(){ 
    $(document).on("keyup", "#Id", function() { 
    $("#Id").val($("#Id").val().replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '').toLowerCase()); 
}); 
}); 
0
[User below code to restrict special character also  

$(h.txtAmount).keydown(function (event) { 
     if (event.shiftKey) { 
      event.preventDefault(); 
     } 
     if (event.keyCode == 46 || event.keyCode == 8) { 
     } 
     else { 
      if (event.keyCode < 95) { 
       if (event.keyCode < 48 || event.keyCode > 57) { 
        event.preventDefault(); 
       } 
      } 
      else { 
       if (event.keyCode < 96 || event.keyCode > 105) { 
        event.preventDefault(); 
       } 
      } 
     } 


    });] 
4

你的文本框:

<input type="text" id="name"> 

您的JavaScript:

$("#name").keypress(function(event) { 
    var character = String.fromCharCode(event.keyCode); 
    return isValid(character);  
}); 

function isValid(str) { 
    return !/[~`[email protected]#$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str); 
} 
1

我使用此代碼修改別人,我所看到的。僅當鍵按下或粘貼的文本傳遞模式測試(匹配)隆重給用戶寫(本實施例中是一個文本輸入,只允許8位)

$("input").on("keypress paste", function(e){ 
    var c = this.selectionStart, v = $(this).val(); 
    if (e.type == "keypress") 
     var key = String.fromCharCode(!e.charCode ? e.which : e.charCode) 
    else 
     var key = e.originalEvent.clipboardData.getData('Text') 
    var val = v.substr(0, c) + key + v.substr(c, v.length) 
    if (!val.match(/\d{0,8}/) || val.match(/\d{0,8}/).toString() != val) { 
     e.preventDefault() 
     return false 
    } 
}) 
相關問題