简体   繁体   English

使用 JavaScript 正则表达式在文本框中只允许正数和负数

[英]Allow only positive and negative numbers in textbox using JavaScript regex

I have a textbox called count.我有一个名为 count 的文本框。 I want to enter only positive and negative numbers in the textbox using JavaScript or jQuery regular expression.我想使用 JavaScript 或 jQuery 正则表达式在文本框中只输入正数和负数。 Do not allow "text" and "decimals" and "special characters" in the textbox.文本框中不允许出现“文本”、“小数”和“特殊字符”。 Even copy and paste also it should take only positive or negative numbers.即使复制和粘贴也应该只取正数或负数。

Important:重要的:

  1. If I copy and paste text or decimal or special character also it should not take.如果我复制并粘贴文本或小数点或特殊字符,也不应采用。 It should take only positive or negative numbers.它应该只取正数或负数。

  2. I want to enter and paste negative values without decimal.我想输入和粘贴没有小数的负值。

  3. Arrow keys should work.箭头键应该可以工作。

  4. Shift , Ctrl , Home , End , Enter like this buttons also should work. ShiftCtrlHomeEndEnter像这样的按钮也应该工作。

Please check the following fiddle and please modify this.请检查以下小提琴并修改它。

Fiddle小提琴

 $(".allownumericwithoutdecimal").on("keypress keyup blur",function (event) { $(this).val($(this).val().replace(/[^\\d].+/, "")); if ((event.which < 48 || event.which > 57)) { event.preventDefault(); } });
 <span>Int</span> <input type="text" name="numeric" class='allownumericwithoutdecimal'> <div>Numeric values only allowed (Without Decimal Point) </div>

I am new for regex.我是正则表达式的新手。 Please help me for do this.请帮我做这件事。

The regex you are looking for is this:您正在寻找的正则表达式是这样的:

Regex: ^-?[0-9]+$正则表达式: ^-?[0-9]+$

Explanation:解释:

  • It checks for optional - ve sign.它检查可选的- ve 符号。 And only allows digits.并且只允许数字。

  • I have used [0-9] instead of \\d because later one means numbers in different languages.我使用了[0-9]而不是\\d因为后来的一个表示不同语言中的数字。

Regex101 Demo Regex101 演示

PS: Am not a Javascript programmer so if anyone want to add fiddle or use this regex, go ahead. PS:我不是 Javascript 程序员,所以如果有人想添加小提琴或使用这个正则表达式,请继续。

This is also achievable without regex using Javascript keypress and charCode.这也可以在没有正则表达式的情况下使用 Javascript keypress 和 charCode 实现。

<input type="number" (keypress)="keypress($event, $event.target.value)" >

keypress(evt, value){

    if (evt.charCode >= 48 && evt.charCode <= 57 || (value=="" && evt.charCode == 45))       
    {  
        return true;
    }
    return false;
}

The given code won't allow user to enter alphabets nor decimal on runtime, just positive and negative integer values.给定的代码不允许用户在运行时输入字母或小数,只能输入正整数和负整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM