javascript - Prevent duplicate comma from being typed into Input Text Box -


i'm using textbox collect numbers only, separated comma. no other characters, not spaces, allowed. 0-9 , comma.

the following function serves purpose, i'd prevent duplicate comma being entered.

correct e.g. 22,444,2,444

incorrect e.g. 22,,444,2,444 or 22,,444,,2,,444

here code i'm using limiting field numbers, , allowing comma:

$(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;  }  }); }); 

i've found may able work @ following link: javascript - prevent duplicate characters in textbox

the example there needs prevent hyphen, charcode 45. comma charcode 44....

but i'm not sure of how implement current code...

any loved, thank you!

in position, not try validate key press, rather validate content of text box when user changes it.

this can e.g. achieved using regular expression:

function validate() {    var input = document.getelementbyid('inputfield').value;      if(input.match(/,{2,}/g)) {      // user entered duplicate comma      alert('no duplicate commas allowed!');    }  }
<input oninput='validate()' id='inputfield' />


you can extend regular expression check input characters other numbers 0 9 , commas:

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

this report e.g. 22,44,d,17 invalid.


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -