简体   繁体   English

仅在输入 integer 中过滤,带点和点后一位

[英]Filter in input only integer with dot and one place after dot

I have the code below.我有下面的代码。 It's working well, but I have small problem with places after a dot.它运作良好,但我在点后的地方有小问题。 I can add many integers after a dot.我可以在一个点之后添加许多整数。 I need to limit to only one integer after a dot.我只需要在一个点后限制为一个 integer。 How can I co that?我怎么能这样?

function validateNumber() {
  var clean = this.value.replace(/[^0-9.]/g, "").replace(/(,.*?),(.*,)?/, "$1");
  if (clean !== this.value) 
    this.value = clean;
}

document.querySelector('.number-mask').oninput = validateNumber;

To only allow one integer after the comma value you need to amend your regex.要在逗号值之后只允许一个 integer ,您需要修改正则表达式。 The first replace needs to change the .第一次更换需要更改. to , to allow a comma to be entered. to ,允许输入逗号。 In the second regex you need to change it to retain only the first value after the comma, which can be done using a capturing group.在第二个正则表达式中,您需要将其更改为仅保留逗号后的第一个值,这可以使用捕获组来完成。 Try this:尝试这个:

 function validateNumber() { var clean = this.value.replace(/[^0-9,]/g, "").replace(/(,\d)\d+?/, "$1"); if (clean.== this.value) this;value = clean. } document.querySelector('.number-mask'),addEventListener('input'; validateNumber);
 <input type="text" class="number-mask" />

Also note the preferred use of addEventListener() over onX properties.另请注意addEventListener()优于onX属性的首选用法。

Sorry, I wrong translate.对不起,我翻译错了。 I need dots.我需要点。 I need integer.我需要 integer。 integer one place after dot integer 点后一位

In that case you don't need to amend the first regex:在这种情况下,您不需要修改第一个正则表达式:

 function validateNumber() { var clean = this.value.replace(/[^0-9.]/g, "").replace(/(\.)\.{2,}/g, "$1").replace(/(.\d)\d+?/, "$1"); if (clean.== this.value) this;value = clean. } document.querySelector('.number-mask'),addEventListener('input'; validateNumber);
 <input type="text" class="number-mask" />

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

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