I have to allow only Debit/Credit card number format in asp.net textbox. Below is a sample screenshot-
Please let me know how to do this with asp.net textbox and I don't have to use validators.
Note: I only have to allow numbers and after every 4 numbers there
should be a hyphen(-).
I would strongly recommend you not to reinvent the bicycle and use jQuery inputmask plugin which will let you do the following:
$("input").inputmask({
mask: "9999 9999 9999 9999",
placeholder: ""
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.js"></script>
<input type="text"/>
Note that in this code I assumed that card number consists of 4 groups of 4 digits each, and it is not always true - it depends on expected cards' payment systems, country etc.
You can easily achieve any result by adding or removing digits in mask.
You can do the following:
<input type="text" onkeypress="return allowNumbersAndHyphen(event)">
function allowNumbersAndHyphen(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
//allowing numbers, left key(37) right key(39) backspace(8) delete(46) and hyphen(45)
var length = $('input').val().length;
if (((charCode == 37 || charCode == 39 || charCode == 8 || charCode == 46 || charCode == 45) || !(charCode > 31 && (charCode < 48 || charCode > 57))) && length <19)
{
return true;
}
else{
return false;
}
}
//put hyphens atomatically
$(document).ready(function(){
$('input').on('keypress', function() {
var temp = $(this).val();
if (temp.length == 4 || temp.length == 9 || temp.length == 14) {
$('input').val(temp + '-');
}
});
$('input').on('blur', function() {
var regex = /^[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}$/;
var cardNumber = $(this).val();
if(regex.test(cardNumber)) {
//success
alert('successful');
}
else {
//show your error
alert('Error');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- begin snippet: js hide: false console: true babel: false -->
Using vanilla javascript
document.getElementById('inp1').onkeypress = verify;
console.clear();
function isKeyValid(key) {
if(key > 47 && key < 58) return true
else if(key === 45) return true;
else return false;
}
function isValidCard(arr, isDash) {
const last = arr[arr.length - 1];
if(last.length === 4 && !isDash) return false;
else if(isDash && last.length !== 4) return false;
else if(isDash && arr.length === 4) return false;
else return true;
}
function verify(e) {
const key = e.keyCode || e.which;
const isDash = key === 45;
const val = e.target.value;
const input = val.split('-');
if (!isKeyValid(key) || !isValidCard(input, isDash)) {
return e.preventDefault();
}
// ...do something
}
How to check textbox validation for two numbers and two decimal values in asp.net with javascript?
For Example whien i press the key in textbox it should allow me only xx.xx format, example : 12.25, 25.50,48.45 etc.
I got the answer.
<div>
<asp:TextBox ID="TextBox2" runat="server"
onkeypress="return isDecimalNumber(event,this);" MaxLength="5">
</asp:TextBox>
</div>
<script type="text/javascript" language="javascript">
var count = 0;
function isDecimalNumber(evt, c) {
count = count + 1;
var charCode = (evt.which) ? evt.which : event.keyCode;
var dot1 = c.value.indexOf('.');
var dot2 = c.value.lastIndexOf('.');
if (count > 2 && dot1 == -1) {
c.value = "";
count = 0;
}
if (dot1 > 2) {
c.value = "";
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
else if (charCode == 46 && (dot1 == dot2) && dot1 != -1 && dot2 != -1)
return false;
return true;
}
</script>
Try this,
$('.TextBox2').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
var text = $(this).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 2)) {
event.preventDefault();
}
});
http://jsfiddle.net/hibbard_eu/vY39r/
$("#amount").on("keyup", function(){
var valid = /^\d{0,2}(\.\d{0,2})?$/.test(this.value),
val = this.value;
if(!valid){
console.log("Invalid input!");
this.value = val.substring(0, val.length - 1);
}
});
i want total amount from price and product quantity dynamically after changing #quantity text-box value.
Here is how i did it. but there's no call to calculate function as i checked in Firefox console. any solutions?
$(document).ready(function(){
$("#quantity").bind('change',calculate);
function calculate()
{
var price = $("#price").val();
var quantity = $("#quantity").val();
var amount = price * quantity;
$("#amount").val(amount);
}
});
You should use format number
$.fn.formatNumber = function() {
$(this).keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 109, 110, 189, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
return this;
};
Then use keyup:
$.fn.setupQty = function() {
$(this).keyup(function(){
if( $('#quantity').val() != '' && $('#price').val() != '') {
var quantity = $(this).val();
var price = $("#price").val();
var amount = price * quantity;
$("#amount").val(amount);
}
else {
$("#amount").val(0);
}
});
return this;
};
$('#quantity').formatNumber().setupQty();
I have a condition to allow user to input only 2 decimal points number and restrict the alphabets and other characters. I used the following function:
function isNumberKeyOnlyWithDecimalFormat(event,value,id){
var val = value;
if (event.shiftKey === true) {
event.preventDefault();
}
if ((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105) ||
event.keyCode == 8 ||
event.keyCode == 9 ||
event.keyCode == 37 ||
event.keyCode == 39 ||
event.keyCode == 46 ||
event.keyCode == 190) {
} else {
event.preventDefault();
}
if(val.indexOf('.') !== -1 && event.keyCode == 190){
event.preventDefault();
}
if ((pointPos = $('#'+id).val().indexOf('.')) >= 0){
$('#'+id).attr("maxLength", pointPos+3);
}
else
$('#'+id).removeAttr("maxLength");
}
It is working fine while first time adding. But it restricts the if i want to edit the digits if it has already 2 decimal place. Can anyone help with this?
Try this. It will check the value each time the focus is gone from the input field, but you can use any event you like. It will parse the value as a float, and then round it to 2 decimal points.
Here is the fiddle: http://jsfiddle.net/sAp9D/
HTML:
<input type="text" id="the_id" />
JavaScript:
var input_field = document.getElementById('the_id');
input_field.addEventListener('change', function() {
var v = parseFloat(this.value);
if (isNaN(v)) {
this.value = '';
} else {
this.value = v.toFixed(2);
}
});
Your question is very hard to understand but if you want to check that a string has only 2 decimals then you can just do this
if( value.match(/\./g).length === 2 ) {
// Number has 2 decimals eg. 1.2.3
} else {
// Number is incorrect eg. 1.2.3.4
}
or if you want 1.2 then
if( value.match(/\./g).length === 1 ) {
// Code....
}
I use the following
// This function will only allow digits
function numericFormat( fld , e , extraStrCheck )
{
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
if ( extraStrCheck )
strCheck += extraStrCheck;
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (whichCode == 13) return true; // Enter
if (whichCode == 8) return true; // Backspace
if (whichCode == 0) return true; // Null
if (whichCode == 9) return true; // Tab
key = String.fromCharCode(whichCode); // Get key value from key code
if ( strCheck.indexOf(key) == -1 ) return false; // Not a valid key
var x = new String(fld.value);
if ( key == '.' )
{
var exp = /\./;
var a = x.search(exp);
if ( a != -1 ) return false;
}
}
// samer code on change or on blur event
function allow2decimal(obj){
var v = parseFloat($(obj).val());
if (isNaN(v)) {
$(obj).value = '';
} else {
newVal = v.toFixed(2);
if(newVal >= 100){
$(obj).val( 100 );
}else{
$(obj).val(newVal);
}
}
}
//usage
<input
onkeypress="return numericFormat( this , event , '.');"
onchange="allow2decimal(this)"
value="0.1"
id="factory_silk" name="factory_silk" />
<html>
<head>
<script type="text/javascript">
function NumAndTwoDecimals(e, field) {
var val = field.value;
var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
if (re.test(val)) {
}
else {
val = re1.exec(val);
if (val) {
field.value = val[0];
}
else {
field.value = "";
}
}
}
</script>
</head>
<body>
<input type="text" name="text" onkeyup="NumAndTwoDecimals(event , this);">
</body>
</html>
$('.number').keypress(function(evt){
var str = $(this).val();
var index = str.indexOf('.');
if(index==-1){index=0;}else{index= index+1;}
var extrapoint = str.indexOf('.',index);
if(extrapoint>0){$(this).val(str.slice(0,-1));}
var charCode = (evt.which) ? evt.which : event.keyCode;
if(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
var validNumber = new RegExp(/^\d*\.?\d*$/);
var lastValid = $(this).val();
if (validNumber.test($(this).val()))
{
lastValid = $(this).val();
}
else
{
$(this).val(lastValid);
}
});
i'm making some input mask that allows only float number. But current problem is I can't check if multiple dots entered. Can you check those dots and prevent it for me?
Live Code: http://jsfiddle.net/thisizmonster/VRa6n/
$('.number').keypress(function(event) {
if (event.which != 46 && (event.which < 47 || event.which > 59))
{
event.preventDefault();
if ((event.which == 46) && ($(this).indexOf('.') != -1)) {
event.preventDefault();
}
}
});
You can check for the period in the same statement.
Also, you need to use the val method to get the value of the element.
Also, you want to check for the interval 48 to 57, not 47 to 59, otherwise you will also allow /, : and ;.
jQuery(document).ready(function() {
$('.float-number').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
Enter Number:
<input type="text" name="number" value="" class="float-number">
</body>
</html>
I think you guys have missed the left right arrows, delete and backspace keys.
$('.number').keypress(function(event) {
if(event.which == 8 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46)
return true;
else if((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
event.preventDefault();
});
I think everybody forgot the case of pasting text with the mouse, in which you can't detect the keystrokes, because there's none. Here's another approach I have been working on.
// only integer or float numbers (with precision limit)
// example element: <input type="text" value="" class="number" name="number" id="number" placeholder="enter number" />
$('.number').on('keydown keypress keyup paste input', function () {
// allows 123. or .123 which are fine for entering on a MySQL decimal() or float() field
// if more than one dot is detected then erase (or slice) the string till we detect just one dot
// this is likely the case of a paste with the right click mouse button and then a paste (probably others too), the other situations are handled with keydown, keypress, keyup, etc
while ( ($(this).val().split(".").length - 1) > 1 ) {
$(this).val($(this).val().slice(0, -1));
if ( ($(this).val().split(".").length - 1) > 1 ) {
continue;
} else {
return false;
}
}
// replace any character that's not a digit or a dot
$(this).val($(this).val().replace(/[^0-9.]/g, ''));
// now cut the string with the allowed number for the integer and float parts
// integer part controlled with the int_num_allow variable
// float (or decimal) part controlled with the float_num_allow variable
var int_num_allow = 3;
var float_num_allow = 1;
var iof = $(this).val().indexOf(".");
if ( iof != -1 ) {
// this case is a mouse paste (probably also other events) with more numbers before the dot than is allowed
// the number can't be "sanitized" because we can't "cut" the integer part, so we just empty the element and optionally change the placeholder attribute to something meaningful
if ( $(this).val().substring(0, iof).length > int_num_allow ) {
$(this).val('');
// you can remove the placeholder modification if you like
$(this).attr('placeholder', 'invalid number');
}
// cut the decimal part
$(this).val($(this).val().substring(0, iof + float_num_allow + 1));
} else {
$(this).val($(this).val().substring(0, int_num_allow));
}
return true;
});
Good for integer and float values. Plus, copy/paste clipboard event.
var el = $('input[name="numeric"]');
el.prop("autocomplete",false); // remove autocomplete (optional)
el.on('keydown',function(e){
var allowedKeyCodesArr = [9,96,97,98,99,100,101,102,103,104,105,48,49,50,51,52,53,54,55,56,57,8,37,39,109,189,46,110,190]; // allowed keys
if($.inArray(e.keyCode,allowedKeyCodesArr) === -1 && (e.keyCode != 17 && e.keyCode != 86)){ // if event key is not in array and its not Ctrl+V (paste) return false;
e.preventDefault();
} else if($.trim($(this).val()).indexOf('.') > -1 && $.inArray(e.keyCode,[110,190]) != -1){ // if float decimal exists and key is not backspace return fasle;
e.preventDefault();
} else {
return true;
};
}).on('paste',function(e){ // on paste
var pastedTxt = e.originalEvent.clipboardData.getData('Text').replace(/[^0-9.]/g, ''); // get event text and filter out letter characters
if($.isNumeric(pastedTxt)){ // if filtered value is numeric
e.originalEvent.target.value = pastedTxt;
e.preventDefault();
} else { // else
e.originalEvent.target.value = ""; // replace input with blank (optional)
e.preventDefault(); // retur false
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="numeric" value="" placeholder="insert value">
[2017-10-31] Vanilla.js
let el = document.querySelector('input[name="numeric"]');
el.addEventListener('keypress',(event) => {
let k = event.key,
t = isNaN(k),
sc = ['Backspace'].indexOf(k) === -1,
d = k === '.',dV = el.value.indexOf('.') > -1,
m = k === '-',mV = el.value.length > 0;
if((t && sc) && ((d && dV) || (m && dV) || (m && mV) || ((t && !d) && (t && !m)))){event.preventDefault();}
},false);
el.addEventListener('paste',(event) => {
if(event.clipboardData.types.indexOf('text/html') > -1){
if(isNaN(event.clipboardData.getData('text'))){event.preventDefault();}
}
},false);
<input type="text" name="numeric">
Your code seems quite fine but overcomplicated.
First, it is $(this).val().indexOf, because you want to do something with the value.
Second, the event.which == 46 check is inside an if clause that's only passed when event.which != 46, which can never be true.
I ended up with this which works: http://jsfiddle.net/VRa6n/3/.
$('.number').keypress(function(event) {
if(event.which < 46
|| event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46
&& $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
});
I found this way to do this,
$.validator.addMethod("currency", function (value, element) {
return this.optional(element) || /^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/.test(value);
}, "Please specify a valid amount");
https://gist.github.com/jonkemp/9094324
HTML
<input type="text" onkeypress="return isFloatNumber(this,event)" />
Javascript
function isFloatNumber(item,evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode==46)
{
var regex = new RegExp(/\./g)
var count = $(item).val().match(regex).length;
if (count > 1)
{
return false;
}
}
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
jsfiddle.net
Using JQuery.
$(document).ready(function()
{
//Only number and one dot
function onlyDecimal(element, decimals)
{
$(element).keypress(function(event)
{
num = $(this).val() ;
num = isNaN(num) || num === '' || num === null ? 0.00 : num ;
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
{
event.preventDefault();
}
if($(this).val() == parseFloat(num).toFixed(decimals))
{
event.preventDefault();
}
});
}
onlyDecimal("#TextBox1", 3) ;
});
One-more plugin, based on Carlos Castillo answer
https://github.com/nikita-vanyasin/jquery.numberfield.js
Adds method to jQuery object:
$('input.my_number_field').numberField(options);
where options is (you can pass any or no options):
{
ints: 2, // digits count to the left from separator
floats: 6, // digits count to the right from separator
separator: "."
}
Using jQuery and allowing negative floats :
// Force floats in '.js_floats_only' inputs
$(document).ready(function() {
$('.js_floats_only').each(function() {
// Store starting value in data-value attribute.
$(this).data('value', this.value);
});
});
$(document).on('keyup', '.js_floats_only', function() {
var val = this.value;
if ( val == '-' ) {
// Allow starting with '-' symbol.
return;
} else {
if ( isNaN(val) ) {
// If value is not a number put back previous valid value.
this.value = $(this).data('value');
} else {
// Value is valid, store it inside data-value attribute.
$(this).data('value', val);
}
}
});
For simple cases and without hardcoding some html instructions would fit that pretty enough
<input type="number" step="0.01"/>
$('.number').keypress(function(event){
if($.browser.mozilla == true){
if (event.which == 8 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 9 || event.keyCode == 16 || event.keyCode == 46){
return true;
}
}
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
This works in all browsers.
<input type="text" data-textboxtype="numeric" />
<script>
$(document).on('keydown', '[data-textboxtype="numeric"]', function (e) {
// Allow: backspace, delete, tab, escape, enter and . and -
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190, 109, 189]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return true;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
return false;
}
return true;
});
</script>
Below Code I am allowing only Digits and Dot symbol.
ASCII characters number starts in 47 and ends with 58 and dot value is 190.
$("#Experince").keyup(function (event) {
debugger
if ((event.which > 47
&& event.which < 58) ||event.which== 190) {
if ($("#Experince").val().length > 3) {
}
} // prevent if not number/dot
else {
$("#Experince").val($("#Experince").val().slice(0, -1))
}
});