jqueryで入力フィールドに特殊文字が入力されないようにするにはどうすればよいですか?
23 に答える
好きなものを許可/禁止するように変更できる正規表現を使用した簡単な例。
$('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;
}
});
入力を英数字のみに制限し、制御文字 (バックスペース、削除、タブなど) とコピーと貼り付けを許可する回答を探していました。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);
});
簡単な答え:「キープレス」イベントを防止します:
$("input").keypress(function(e){
var charCode = !e.charCode ? e.which : e.charCode;
if(/* Test for special character */ )
e.preventDefault();
})
長い答え: jquery.alphanumのようなプラグインを使用してください
ソリューションを選択する際に考慮すべき点がいくつかあります。
- 貼り付けたテキスト
- バックスペースや F5 などの制御文字は、上記のコードによって防止される場合があります。
- é、í、ä など
- アラビア語か中国語か...
- クロスブラウザの互換性
この領域は、サードパーティのプラグインを使用することを保証するのに十分複雑だと思います. 利用可能なプラグインをいくつか試してみましたが、それぞれにいくつかの問題が見つかったので、先に進んでjquery.alphanumを書きました。コードは次のようになります。
$("input").alphanum();
または、より細かく制御するには、いくつかの設定を追加します。
$("#username").alphanum({
allow : "€$£",
disallow : "xyz",
allowUpper : false
});
それが役に立てば幸い。
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'});
これは、ユーザーが文字「a」を入力できないようにする例です。
$(function() {
$('input:text').keydown(function(e) {
if(e.keyCode==65)
return false;
});
});
キーコードの参照はこちら:
http://www.expandinghead.net/keycode.html
テキストボックスの 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;
}
キー押下時の特殊文字を制限します。キー コードのテスト ページは次のとおりです: 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();
}
});
Angular では、テキスト フィールドに適切な通貨形式が必要でした。私の解決策:
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;
}
...
数字だけ:
$('input.time').keydown(function(e) { if(e.keyCode>=48 && e.keyCode<=57) { true を返す; } else { false を返す; } });
または「:」を含む時間
$('input.time').keydown(function(e) { if(e.keyCode>=48 && e.keyCode<=58) { true を返す; } else { false を返す; } });
削除とバックスペースも含む:
$('input.time').keydown(function(e) { if((e.keyCode>=46 && e.keyCode<=58) || e.keyCode==8) { return true; } else { return間違い; } });
残念ながらiMACでは動かない
Dale の回答に対する Alex のコメントについてコメントしたいと思います。不可能です(最初にどれだけの「担当者」が必要ですか?それはすぐには起こりません..奇妙なシステムです。)答えとして:
[a-zA-Z0-9\b] のように \b を正規表現定義に追加することで、バックスペースを追加できます。または、多かれ少なかれ「エキゾチックではない」文字 (バックスペースなどの制御文字も含む) を含む、ラテン語の範囲全体を単純に許可します: ^[\u0000-\u024F\u20AC]+$
ユーロ記号 (20ac) があるのはラテン語以外の実際の Unicode 文字だけです。他に必要なものは何でも追加してください。
コピー&ペーストで入力された入力も処理するには、単純に「変更」イベントにバインドし、そこでも入力をチェックします - 削除またはストライピング / 「サポートされていない文字」などのエラー メッセージを表示します。
if (!regex.test($j(this).val())) {
alert('your input contained not supported characters');
$j(this).val('');
return false;
}
はい、次のように 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)"/>
HTML の場合:
<input type="text" (keypress)="omitSpecialChar($event)"/>
JS で:
omitSpecialChar(event) {
const keyPressed = String.fromCharCode(event.keyCode);
const verifyKeyPressed = /^[a-zA-Z\' \u00C0-\u00FF]*$/.test(keyPressed);
return verifyKeyPressed === true;
}
この例では、アクセントを入力できます。