简体   繁体   English

输入数字验证 - 限制只输入数字或数字,int和float两者

[英]Input number validation - Restrict to enter only numbers or digits, int & float both

How to restrict the input field to enter only numbers/digits int and float both. 如何限制输入字段只输入数字/数字int和浮动两者。 Sometimes we need to allow both integer as well as float value for fields like amount, so in that case the validation is required. 有时我们需要允许像amount这样的字段的整数和浮点值,因此在这种情况下需要验证。 There are no of solutions available but they are of large size code. 没有可用的解决方案,但它们具有大尺寸代码。 So need a short but effective code. 因此需要一个简短但有效的代码。

<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />

No need for the long code for number input restriction just try this code. 不需要数字输入限制的长代码只需尝试此代码。

It also accepts valid int & float both values. 它还接受有效的int和float两个值。

Javascript Approach Javascript方法

 onload =function(){ var ele = document.querySelectorAll('.number-only')[0]; ele.onkeypress = function(e) { if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false; } ele.onpaste = function(e){ e.preventDefault(); } } 
 <p> Input box that accepts only valid int and float values.</p> <input class="number-only" type=text /> 

jQuery Approach jQuery方法

 $(function(){ $('.number-only').keypress(function(e) { if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false; }) .on("cut copy paste",function(e){ e.preventDefault(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> Input box that accepts only valid int and float values.</p> <input class="number-only" type=text /> 

UPDATE UPDATE

The above answers are for most common use case - validating input as a number. 以上答案适用于大多数常见用例 - 将输入验证为数字。

But as per comments, some wants to allow few special cases like negative numbers & showing the invalid keystrokes to user before removing it, so below is the code snippet for such special use cases. 但是根据评论,有些人希望允许一些特殊情况,比如负数,并在删除之前向用户显示无效的击键,因此下面是这些特殊用例的代码片段。

 $(function(){ $('.number-only').keyup(function(e) { if(this.value!='-') while(isNaN(this.value)) this.value = this.value.split('').reverse().join('').replace(/[\\D]/i,'') .split('').reverse().join(''); }) .on("cut copy paste",function(e){ e.preventDefault(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> Input box that accepts only valid int and float values.</p> <input class="number-only" type=text /> 

One-liner solution #1: 单线解决方案#1:

Use <input type="number"> with the step attribute. <input type="number">step属性一起使用。

<input type="number" step="0.0001"> // The user can enter up to 4 decimal places.

<input type="number" step="any"> // Not supported in all browsers, but permits numbers of any decimal precision.

You can also use the min and/or max attributes to set the minimum value and/or the maximum value. 您还可以使用min和/或max属性设置最小值和/或最大值。


One-liner solution #2: 单线解决方案#2:

Use a regular text input element with a RegExp pattern attribute. 使用带有RegExp pattern属性的常规文本input元素。

<input type="text" pattern="^-?([0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)$">

This RegExp accepts numbers beginning with a dot ( . ) and/or a negative sign ( - ). 此RegExp接受以点( . )和/或负号( - )开头的数字。

First things first. 首先要做的事情。 I prefer showing the invalid keystrokes rather than preventing them. 我更喜欢显示无效的击键而不是阻止它们。 User Experience Stack Exchange seems to agree at the moment ( see this question ). 用户体验Stack Exchange目前似乎同意( 请参阅此问题 )。

That said, not everyone agrees, so let's see what we can do. 也就是说,不是每个人都同意,所以让我们看看我们能做些什么。

Second. 第二。 This doesn't replace a validation step. 这不会取代验证步骤。 There are certain valid keystroke combinations that are not valid numbers, but need to be permitted in order to enter valid numbers. 某些有效的击键组合不是有效数字,但需要被允许才能输入有效数字。 For example, the user could type a decimal mark (full stop or comma, depending on the language they are using), and then leave the text box, and you don't have a valid number. 例如,用户可以键入小数点(句号或逗号,具体取决于他们使用的语言),然后保留文本框,并且您没有有效的数字。 The following strings are all starts of numbers, but not yet valid: 以下字符串都是数字的开头,但尚未生效:

  • .
  • -. - 。
  • ,
  • -, - , -

The first two are the start of .5 or -.5, while the last two are the same in the various languages that use a comma instead of a full stop for the decimal mark. 前两个是.5或-.5的开头,而后两个在使用逗号而不是十进制标记的句点的各种语言中是相同的。

This brings us to the (already rejected) 这带给我们(已经被拒绝)

 <input type="number" step="any"> 

Of course, you will have to include a JavaScript script to fix non-modern browsers, but those are available. 当然,您必须包含一个JavaScript脚本来修复非现代浏览器,但这些浏览器都可用。 In theory, these should also work correctly when the user works in a language that uses the comma instead of the full stop for the decimal mark. 理论上,当用户使用逗号而不是小数点的句点来运行时,这些也应该正常工作。 Even better, since users usually use only one browser, and since they will be used to how input number works in that browser, and since they will spend most of their time on other websites than yours, they may get confused if your website does not behave the same way they are used to. 更好的是,由于用户通常只使用一个浏览器,并且因为他们将习惯输入数字在该浏览器中的工作方式,并且因为他们将大部分时间花在除您之外的其他网站上,如果您的网站没有,他们可能会感到困惑表现与他们习惯的方式相同。

But maybe you still want to make your own solution. 但也许你还想制定自己的解决方案。 If all else fails, I would go with a regular expression (yes, I know, I now have two problems). 如果一切都失败了,我会用正则表达式(是的,我知道,我现在有两个问题)。 I don't believe in allowing spaces, so I limit it to a negative sign, digits, and one decimal mark (whichever they are using). 我不相信允许空格,因此我将其限制为负号,数字和一个小数点(无论它们使用哪个)。 For example: 例如:

 $('.rational-number').on('keypress', function(e) { if (e.charCode >= 32 && e.charCode < 127 && !/^-?\\d*[.,]?\\d*$/.test(this.value + '' + String.fromCharCode(e.charCode))) { return false; } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type-"text" class="rational-number"> 

This ALMOST works. 这个ALMOST有效。 The only problem I now have is, it assumes any character you type goes at the end of the string. 我现在唯一的问题是,它假设你输入的任何字符都在字符串的末尾。 This is fine except for the '-' for negative numbers, which is only allowed at the beginning. 这是正常的,除了负数的' - ',只允许在开头。 So you can type -5.4, but if you type 5.4 and then hit the home key or left arrow back to the beginning, it won't let you make it negative. 所以你可以输入-5.4,但是如果你输入5.4然后点击主页键或左箭头回到开头,它就不会让你输入负数。

It also won't deal with pasting. 它也不会处理粘贴。 Paste is a complicated topic. 粘贴是一个复杂的主题。 I don't agree with rejecting all paste operations. 我不同意拒绝所有粘贴操作。 I feel the best option here is to just let the user paste and let the validator pick up any invalid numbers. 我觉得这里最好的选择就是让用户粘贴并让验证者选择任何无效的数字。

You can add a pattern attribute to the input field. 您可以将pattern属性添加到输入字段。 If the input value doesn't match the pattern, you can style the input field and/or show an error message by using the css selector :invalid : 如果输入值与模式不匹配,则可以使用css选择器设置输入字段的样式和/或显示错误消息:invalid

 .error-msg { display: none; /* Hide by default */ } .number-only:invalid { background: pink; } .number-only:invalid + .error-msg { display: inline; } 
 <input type='tel' class='number-only' pattern='[+\\-]?\\d*\\.?\\d+' /> <span class='error-msg'>Please enter a valid integer or float value.</span> 

Some notes: 一些说明:

  • type='tel' makes mobile browsers open a number keyboard, but of course you can also set the type to text . type='tel'使移动浏览器打开数字键盘,当然你也可以将类型设置为text
  • Browser support for the pattern input attribute: http://caniuse.com/#feat=input-pattern 浏览器对pattern输入属性的支持: http//caniuse.com/#feat=input-pattern
  • Browser support for the :invalid css selector: http://caniuse.com/#feat=form-validation 浏览器支持:invalid css选择器: http//caniuse.com/#feat=form-validation
  • The pattern regex doesn't support exponential notation, eg 1.23e4 . 模式正则表达式不支持指数表示法,例如1.23e4
  • The pattern regex doesn't allow spaces – they are not valid in int and float notation, but allowing them might improve user experience. 模式正则表达式不允许使用空格 - 它们在int和float表示法中无效,但允许它们可能会改善用户体验。

Call one jquery function in onkeypress of the textbox. 在文本框的onkeypress中调用一个jquery函数。 In that function use the respective ascii code to restrict input. 在该函数中使用相应的ascii代码来限制输入。

User can not enter Decimal value in js. 用户无法在js中输入十进制值。 Try using this code : 尝试使用此代码:

if(document.getElementById(id).value.indexOf('.') != -1){
    print "do not Enter decimal nuber";
}

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

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