输入只允许一个小数点

时间:2017-02-04 18:02:21

标签: javascript regex

我正在尝试在输入时格式化数字,您只能插入有效数字。我有一切工作,除了小数。输入框允许我插入尽可能多的小数,但我只想允许一个(见最后replace())。

element.oninput = e => {
    let value = e.currentTarget.value;
    let result = value
        // Remove anything that isn't valid in a number
        .replace(/[^0-9-.]/g, '')
        // Remove all dashes unless it is the first character
        .replace(/(?!^)-/g, '')
        // Remove all periods unless it is the last one
        .replace(/(?!)\./g, '');
    element.value = result;
}

https://jsfiddle.net/c4f1L3kv/1/

以下是一些有效的输入:

123.123
-123.12
123
-123
.123
-.123

以下是一些无效输入:

123-123
1-2-3
123.123.123
123-123..12

2 个答案:

答案 0 :(得分:3)

var element = document.querySelector('input');


element.oninput = e => {
    let value = e.currentTarget.value;
    let result = value
        .replace(/[^0-9-.]/g, '')
        .replace(/(?!^)-/g, '')
        // prevent inserting dots after the first one
        .replace(/([^.]*\.[^.]*)\./g, '$1');
    element.value = result;
}
<input/> 

答案 1 :(得分:3)

如果您只想匹配一个句点字符(如果后面跟着另一个句点字符),那么您可以在下面的表达式中使用positive lookahead之类的字符:

/\.(?=.*\.)/g

说明:

  • \. - 匹配文字.字符
  • (?= - 开始积极向前看
    • .*\. - 匹配零个或多个字符,直到文字.字符。
  • ) - 关闭积极前瞻

&#13;
&#13;
var element = document.querySelector('input');
element.addEventListener('input', (event) => {
  event.target.value = event.target.value
    // Remove anything that isn't valid in a number
    .replace(/[^\d-.]/g, '')
    // Remove all dashes unless it is the first character
    .replace(/(?!^)-/g, '')
    // Remove all periods unless it is the last one
    .replace(/\.(?=.*\.)/g, '');
});
&#13;
<input type="text" />
&#13;
&#13;
&#13;

根据您的评论:

如果您希望阻止用户在字符串末尾添加句点字符(如果已存在句点字符),则可以使用表达式/(\..*)\.$/并将第一个捕获组替换为自身,这将有效地删除捕获组中的任何内容(即最后一个句点字符)。

&#13;
&#13;
var element = document.querySelector('input');
element.addEventListener('input', (event) => {
  event.target.value = event.target.value
    // Remove anything that isn't valid in a number
    .replace(/[^\d-.]/g, '')
    // Remove all dashes unless it is the first character
    .replace(/(?!^)-/g, '')
    // Remove the last period if there is already one
    .replace(/(\..*)\.$/, '$1')
    // Remove all periods unless it is the last one
    .replace(/\.(?=.*\.)/g, '');
});
&#13;
<input type="text" />
&#13;
&#13;
&#13;