防止将重复的逗号输入到输入文本框中

时间:2016-05-25 03:34:29

标签: javascript jquery

我正在使用文本框仅收集数字,用逗号分隔。不允许使用其他字符,甚至空格。只有0-9和一个逗号。

以下功能符合我的目的,但我现在要防止输入重复的逗号。

正确 例如22,444,2,444

不正确的 例如22,444,2,444或22,444,2,444

以下是我用于将字段限制为数字的代码,并且只允许使用逗号:

$(document).ready(function(){
$("#customPrices").keypress(function (e) {


if (e.which != 8 && e.which != 0 && String.fromCharCode(e.which) != ',' && (e.which < 48 || e.which > 57))
{

//display error message
if($( "#errmsg" ).is(':hidden'))
{
$( "#errmsg" ).fadeIn();
}
return false;

}

});
});

我找到了可以在以下链接中工作的内容: Javascript Help - prevent duplicate characters in textbox

这个例子需要阻止连字符,即charCode 45.逗号是charCode 44 ....

但我不确定如何将其实现到我当前的代码中......

任何帮助都会非常受欢迎,谢谢!

2 个答案:

答案 0 :(得分:1)

在您的位置,我不会尝试验证按键,而是在用户更改时验证文本框的内容

这可以是例如使用正则表达式实现:

&#13;
&#13;
function validate() {
  var input = document.getElementById('inputField').value;

  if(input.match(/,{2,}/g)) {
    // the user entered a duplicate comma
    alert('No duplicate commas allowed!');
  }
}
&#13;
<input oninput='validate()' id='inputField' />
&#13;
&#13;
&#13;

您还可以将正则表达式扩展为检查数字0到9以及逗号以外的字符的输入:

/(,{2,}|[^,0-9])/g

这也将报告,例如22,44,d,17无效。

答案 1 :(得分:1)

add the below condition:
1) take the existing value
2) check the last char is (,) and current char also (,) and validate
 var customPrices = $("#customPrices").val();

String.fromCharCode(e.which) == ',' && String.fromCharCode(e.which) == 
customPrices.charAt(customPrices.length-1)

or 
String.fromCharCode(e.which) == ',' && customPrices.charAt(customPrices.length-1) == ','
相关问题