user2255785 user2255785 - 1 year ago 50
Javascript Question

Prevent duplicate comma from being typed into Input Text Box

I'm using a textbox to collect numbers only, separated by a comma. No other characters, not even spaces, are allowed. Only 0-9 and a comma.

The following function serves my purpose, but I'd like to now prevent a duplicate comma from being entered.

e.g. 22,444,2,444

e.g. 22,,444,2,444 OR 22,,444,,2,,444

Here is the code I'm using for limiting the field to numbers, and allowing only a comma:

$("#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;



I've found something that may be able to work at the following link:
Javascript Help - prevent duplicate characters in textbox

The example there needs to prevent a hyphen, which is charCode 45. A comma is charCode 44....

But I'm not sure of how to implement it into my current code...

Any help would be really loved, thank you!

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) == 

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