javascript - Format credit card number -
how format , validate credit card number spaces between each 4 digit while typing:
eg: 4464 6846 4354 3564
i have tried:
$('.creditno').keyup(function() { cc = $(this).val().split("-").join(""); cc = cc.match(new regexp('.{1,4}$|.{1,4}', 'g')).join("-"); $(this).val(cc); });
please help
try this:
function cc_format(value) { var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '') var matches = v.match(/\d{4,16}/g); var match = matches && matches[0] || '' var parts = [] (i=0, len=match.length; i<len; i+=4) { parts.push(match.substring(i, i+4)) } if (parts.length) { return parts.join(' ') } else { return value } }
note: check detailed information https://www.peterbe.com/plog/cc-formatter.
to restrict user enter number only:
javascript way
<input type="text" id="txt_cardnumber" name="txt_cardnumber" onkeypress="return checkdigit(event)"> function checkdigit(event) { var code = (event.which) ? event.which : event.keycode; if ((code < 48 || code > 57) && (code > 31)) { return false; } return true; }
or
function checkdigit() { var allowedchars = "0123456789"; var entryval = document.getelementbyid('txt_cardnumber').value(); var flag; for(var i=0; i<entryval.length; i++){ flag = false; for(var j=0; j<allowedchars.length; j++){ if(entryval.charat(i) == allowedchars.charat(j)) { flag = true; } } if(flag == false) { entryval = entryval.replace(entryval.charat(i),""); i--; } } return true; }
html5 way
<input type="text" id="txt_cardnumber" name="txt_cardnumber" pattern="[0-9.]+"> <input type="number" id="txt_cardnumber" name="txt_cardnumber">
jquery way
$("#txt_cardnumber").keypress(function (e) { if ((e.which < 48 || e.which > 57) && (e.which !== 8) && (e.which !== 0)) { return false; } return true; });
note: please check here more information various key code.
Comments
Post a Comment