如何使用 jquery 阻止或限制输入字段中的特殊字符?

发布于 2024-07-22 05:07:44 字数 34 浏览 5 评论 0原文

如何使用 jquery 阻止在输入字段中输入特殊字符?

How do I block special characters from being typed into an input field with jquery?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(27

喜爱纠缠 2024-07-29 05:07:45

一个使用正则表达式的简单示例,您可以更改它以允许/禁止您喜欢的任何内容。

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

A simple example using a regular expression which you could change to allow/disallow whatever you like.

$('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;
    }
});
原野 2024-07-29 05:07:45

我正在寻找一个答案,将输入限制为仅字母数字字符,但仍然允许使用控制字符(例如,退格键、删除键、制表符)和复制+粘贴。 我尝试提供的答案都不满足所有这些要求,因此我使用 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);
});

I was looking for an answer that restricted input to only alphanumeric characters, but still allowed for the use of control characters (e.g., backspace, delete, tab) and copy+paste. None of the provided answers that I tried satisfied all of these requirements, so I came up with the following using the input event.

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

Edit:
As rinogo pointed out in the comments, the above code snippet forces the cursor to the end of the input when typing in the middle of the input text. I believe the code snippet below solves this problem.

$('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);
});
对岸观火 2024-07-29 05:07:45

简短回答:防止“按键”事件:

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

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

长回答:使用像 jquery.alphanum

选择解决方案时需要考虑以下几点:

  • 粘贴文本
  • 上面的代码可能会阻止
  • 退格键或 F5 等控制字符。 é、í、ä 等
  • 阿拉伯语或中文...
  • 跨浏览器兼容性

我认为这个领域足够复杂,足以保证使用第 3 方插件。 我尝试了几个可用的插件,但发现每个插件都有一些问题,所以我继续编写 jquery.alphanum 。 代码如下所示:

$("input").alphanum();

或者为了更细粒度的控制,添加一些设置:

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

希望它有帮助。

Short answer: prevent the 'keypress' event:

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

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

Long answer: Use a plugin like jquery.alphanum

There are several things to consider when picking a solution:

  • Pasted text
  • Control characters like backspace or F5 may be prevented by the above code.
  • é, í, ä etc
  • Arabic or Chinese...
  • Cross Browser compatibility

I think this area is complex enough to warrant using a 3rd party plugin. I tried out several of the available plugins but found some problems with each of them so I went ahead and wrote jquery.alphanum. The code looks like this:

$("input").alphanum();

Or for more fine-grained control, add some settings:

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

Hope it helps.

飘落散花 2024-07-29 05:07:45

使用简单的内联 onkeypress 事件。

 <input type="text" name="count"  onkeypress="return /[0-9a-zA-Z]/i.test(event.key)">

Use simple onkeypress event inline.

 <input type="text" name="count"  onkeypress="return /[0-9a-zA-Z]/i.test(event.key)">

少跟Wǒ拽 2024-07-29 05:07:45

使用HTML5的模式输入属性!

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

Use HTML5's pattern input attribute!

<input type="text" pattern="^[a-zA-Z0-9]+$" />
冷血 2024-07-29 05:07:45

使用正则表达式允许/禁止任何内容。 此外,对于比接受的答案稍微更强大的版本,可以通过首先传递按键事件并允许没有与其关联的键值的字符(退格键、制表符、箭头键、删除等)来完成根据键码而不是值检查键。

$('#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.,/ $@()]+$");
            var key = event.key;
            if (!regex.test(key)) {
                event.preventDefault();
                return false;
            }
            break;
        }
});

Use regex to allow/disallow anything. Also, for a slightly more robust version than the accepted answer, allowing characters that don't have a key value associated with them (backspace, tab, arrow keys, delete, etc.) can be done by first passing through the keypress event and check the key based on keycode instead of value.

$('#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.,/ $@()]+$");
            var key = event.key;
            if (!regex.test(key)) {
                event.preventDefault();
                return false;
            }
            break;
        }
});
給妳壹絲溫柔 2024-07-29 05:07:45

您的文本框:

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

您的 JavaScript:

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

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

Your textbox:

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

Your javascript:

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

function isValid(str) {
    return !/[~`!@#$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
治碍 2024-07-29 05:07:45

看一下 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'});

Take a look at the jQuery alphanumeric plugin. 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'});
爱的十字路口 2024-07-29 05:07:45

这是一个阻止用户

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

});
});

在此处键入字符“a”键代码的示例:
http://www.expandinghead.net/keycode.html

this is an example that prevent the user from typing the character "a"

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

});
});

key codes refrence here:
http://www.expandinghead.net/keycode.html

小鸟爱天空丶 2024-07-29 05:07:45

我使用这段代码修改我看到的其他代码。 仅当按下的按键或粘贴的文本通过模式测试(匹配)时,才对用户写入(此示例是仅允许 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
    }
})

I use this code modifying others that I saw. Only grand to the user write if the key pressed or pasted text pass the pattern test (match) (this example is a text input that only allows 8 digits)

$("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
    }
})
脱离于你 2024-07-29 05:07:45
$(function(){
      $('input').keyup(function(){
        var input_val = $(this).val();
        var inputRGEX = /^[a-zA-Z0-9]*$/;
        var inputResult = inputRGEX.test(input_val);
          if(!(inputResult))
          {     
            this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
          }
       });
    });
$(function(){
      $('input').keyup(function(){
        var input_val = $(this).val();
        var inputRGEX = /^[a-zA-Z0-9]*$/;
        var inputResult = inputRGEX.test(input_val);
          if(!(inputResult))
          {     
            this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
          }
       });
    });
浅浅淡淡 2024-07-29 05:07:45

在文本框的 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;
}

Write some javascript code on onkeypress event of textbox.
as per requirement allow and restrict character in your textbox

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;
}

沒落の蓅哖 2024-07-29 05:07:45

替换特殊字符、空格并转换为小写

$(document).ready(function (){
  $(document).on("keyup", "#Id", function () {
  $("#Id").val($("#Id").val().replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '').toLowerCase());
 }); 
});

To replace special characters, space and convert to lower case

$(document).ready(function (){
  $(document).on("keyup", "#Id", function () {
  $("#Id").val($("#Id").val().replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '').toLowerCase());
 }); 
});
谁的年少不轻狂 2024-07-29 05:07:45

此操作不需要 jQuery

您可以使用纯 JavaScript 来实现此操作,您可以将其放在 onKeyUp 事件中。

限制 - 特殊字符

e.target.value = e.target.value.replace(/[^\w]|_/g, '').toLowerCase()

接受 - 仅数字

e.target.value = e.target.value.replace(/[^0-9]/g, '').toLowerCase()

接受 - 仅小字母

e.target.value = e.target.value.replace(/[^0-9]/g, '').toLowerCase()

我可以为更多场景编写,但我必须保留具体答案。

注意它将与 jquery、react、Angular 等一起使用。

You don't need jQuery for this action

You can achieve this using plain JavaScript, You can put this in the onKeyUp event.

Restrict - Special Characters

e.target.value = e.target.value.replace(/[^\w]|_/g, '').toLowerCase()

Accept - Number only

e.target.value = e.target.value.replace(/[^0-9]/g, '').toLowerCase()

Accept - Small Alphabet only

e.target.value = e.target.value.replace(/[^0-9]/g, '').toLowerCase()

I could write for some more scenarios but I have to maintain the specific answer.

Note It will work with jquery, react, angular, and so on.

甜扑 2024-07-29 05:07:45

是的,您可以使用 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)"/>

Yes you can do by using jQuery as:

<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>

and script for your user_availability.php will be:

<?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";
    }
}
?>

I tried to add for / and \ but not succeeded.


You can also do it by using javascript & code will be:

<!-- 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)"/>
倚栏听风 2024-07-29 05:07:45

想评论亚历克斯对戴尔答案的评论。 不可能(首先需要多少“代表”?这不会很快发生......奇怪的系统。)
因此,作为答案:

可以通过将 \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;
}

Wanted to comment on Alex's comment to Dale's answer. Not possible (first need how much "rep"? That wont happen very soon.. strange system.)
So as an answer:

Backspace can be added by adding \b to the regex definition like this: [a-zA-Z0-9\b].
Or you simply allow the whole Latin range, including more or less anything "non exotic" characters (also control chars like backspace): ^[\u0000-\u024F\u20AC]+$

Only real unicode char outside latin there is the euro sign (20ac), add whatever you may need else.

To also handle input entered via copy&paste, simply also bind to the "change" event and check the input there too - deleting it or striping it / giving an error message like "not supported characters"..

if (!regex.test($j(this).val())) {
  alert('your input contained not supported characters');
  $j(this).val('');
  return false;
}
迷路的信 2024-07-29 05:07:45

限制按键上的特殊字符。 这是关键代码的测试页: 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;
}

...

Restrict specials characters on keypress. Here's a test page for key codes: 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();
   }
});

In Angular, I needed a proper currency format in my textfield. My solution:

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

In the html add the directive

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

and in the corresponding angular controller I only allow there to be only 1 period, convert text to number and add number rounding on 'blur'

...

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;
}

...
雪若未夕 2024-07-29 05:07:45

仅数字:

$('input.time').keydown(function(e) {
    return e.keyCode >= 48 && e.keyCode <= 57);
});

对于包括 的时间:57 替换为 58。 还包括删除和退格:

return (e.keyCode >= 46 && e.keyCode <= 58) || e.keyCode == 8;

Just the numbers:

$('input.time').keydown(function(e) {
    return e.keyCode >= 48 && e.keyCode <= 57);
});

For time including : replace 57 with 58. To also include delete and backspace:

return (e.keyCode >= 46 && e.keyCode <= 58) || e.keyCode == 8;
街角迷惘 2024-07-29 05:07:45
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
if($(this).val().indexOf('.') == 0) {
    $(this).val("");
}

最简单方法。

这是使用 indexOf 验证输入是否以 开头的

$(this).val($(this).val().replace(/[^0-9\.]/g,''));
if($(this).val().indexOf('.') == 0) {
    $(this).val("");
}

This is the simplest way

indexOf is used to validate if the input started with .

傲性难收 2024-07-29 05:07:45
/**
     * Forbids special characters and decimals
     * Allows numbers only
     * */
    const numbersOnly = (evt) => {

        let charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode === 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }

        let inputResult = /^[0-9]*$/.test(evt.target.value);
        if (!inputResult) {
            evt.target.value = evt.target.value.replace(/[^a-z0-9\s]/gi, '');
        }

        return true;
    }
/**
     * Forbids special characters and decimals
     * Allows numbers only
     * */
    const numbersOnly = (evt) => {

        let charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode === 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }

        let inputResult = /^[0-9]*$/.test(evt.target.value);
        if (!inputResult) {
            evt.target.value = evt.target.value.replace(/[^a-z0-9\s]/gi, '');
        }

        return true;
    }
新人笑 2024-07-29 05:07:45

在 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;
}

在此示例中可以输入重音符号。

In HTML:

<input type="text" (keypress)="omitSpecialChar($event)"/>

In JS:

omitSpecialChar(event) {
    const keyPressed = String.fromCharCode(event.keyCode);
    const verifyKeyPressed = /^[a-zA-Z\' \u00C0-\u00FF]*$/.test(keyPressed);
    return verifyKeyPressed === true;
}

In this example it is possible to type accents.

莳間冲淡了誓言ζ 2024-07-29 05:07:45

文本框中仅允许数字(限制字母和特殊字符)

/* Code:
   48-57 - Numbers
   8 - Backspace
   35 - Home key
   36 - End key
   37-40 - Arrow keys
   46 - Delete key */
function restrictAlphabets(e) {
    var x = e.which || e.keycode;
    return (x >= 48 && x <= 57) || x == 8 ||
        (x >= 35 && x <= 40) || x == 46;
}

Allow only numbers in TextBox (Restrict Alphabets and Special Characters)

/* Code:
   48-57 - Numbers
   8 - Backspace
   35 - Home key
   36 - End key
   37-40 - Arrow keys
   46 - Delete key */
function restrictAlphabets(e) {
    var x = e.which || e.keycode;
    return (x >= 48 && x <= 57) || x == 8 ||
        (x >= 35 && x <= 40) || x == 46;
}
少跟Wǒ拽 2024-07-29 05:07:45

使用下面的代码也可以限制特殊字符

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

Use below code to also restrict special characters

$(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();
            }
        }
    }
});
友谊不毕业 2024-07-29 05:07:45
$(document).ready(function() {
    $('#Description').bind('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);
        if (!(checkEmpty($("#Description").val()))) {
            $("#Description").val("");
        } //1Apr2022 code end
    });
    $('#Description').on('change', function() {
        if (!(checkEmpty($("#Description").val()))) {
            $("#Description").val("");
        } //1Apr2022 code end
    });
});

function checkEmpty(field) { //1Apr2022 new code 
    if (field == "" ||
        field == null ||
        field == "undefinied") {

        return false;
    } else if (/^\s*$/.test(field)) {
        return false;
    } else {
        return true;
    }
}
$(document).ready(function() {
    $('#Description').bind('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);
        if (!(checkEmpty($("#Description").val()))) {
            $("#Description").val("");
        } //1Apr2022 code end
    });
    $('#Description').on('change', function() {
        if (!(checkEmpty($("#Description").val()))) {
            $("#Description").val("");
        } //1Apr2022 code end
    });
});

function checkEmpty(field) { //1Apr2022 new code 
    if (field == "" ||
        field == null ||
        field == "undefinied") {

        return false;
    } else if (/^\s*$/.test(field)) {
        return false;
    } else {
        return true;
    }
}
凉墨 2024-07-29 05:07:45

尝试这个 JavaScript 代码,这是限制输入中特殊字符的简单方法。

源代码:限制特殊字符

$('input').bind('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);
});

Try this JavaScript Code it's a simple way to restrict special characters from the input.

Source code: Restrict special characters

$('input').bind('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);
});
满栀 2024-07-29 05:07:45

这是我的一句话方法......

<input type="text" onkeyup="this.value = this.value.replace(/[^0-9a-zA-Z \-]/g, '');">

它可以处理按键、复制粘贴和点击自动完成建议。 特殊字符会短暂出现,但会立即消失。

Here's my one-liner approach...

<input type="text" onkeyup="this.value = this.value.replace(/[^0-9a-zA-Z \-]/g, '');">

It can handle key presses, copy-pasting and clicks from auto-complete suggestions. There's a momentary appearance of the special characters but will disappear immediately.

醉生梦死 2024-07-29 05:07:45

更增强的形式是:

$('input[type=text]').on('input', function() {
    var c = this.selectionStart,
        r = /[^a-z ]/gi,
        v = $(this).val();
    if (r.test(v)) {
        $(this).val(v.replace(r, ''));
        c--;
    }
    this.setSelectionRange(c, c);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

因为它也允许您输入空格,并且它只会针对输入文本的输入字段,并且不会打扰其他输入字段,例如电子邮件、密码等,因为通常我们在电子邮件和密码字段中需要特殊字符

A more enhanced form would be:

$('input[type=text]').on('input', function() {
    var c = this.selectionStart,
        r = /[^a-z ]/gi,
        v = $(this).val();
    if (r.test(v)) {
        $(this).val(v.replace(r, ''));
        c--;
    }
    this.setSelectionRange(c, c);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Because it will allow you to enter space as well and it will only target the input fields with type text and wont bother the other input fields like email, password etc as normally we need special characters in email and password field

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文