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);
}
});
Related
I been trying to create validation function for input to allow only numeric with two decimal point And max value 99999999.99.
This is what I have tried so far but doesn't seems to be working.
$('#TXTCOST').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
var input = $(this).val();
if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
event.preventDefault();
}
var arr = input.split('.');
if (arr.length == 1 && parseFloat(arr[0]) >= 99999999) {
event.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="TXTCOST"/>
My example below uses a simple regex check for 1-8 digits number with optional 0-2 decimal points:
Edit: Now the code prevents the entry of wrong value. This is done in 2 stages
On key press, make a backup of the current input value then limit user input to allowed keys
Validate current input then revert back to the old value if the new value is invalid.
let allowed_keys = [8, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 190];
let my_regex = /^([0-9]{0,8})(\.{1,1}[0-9]{0,2})?$/;
let old_val;
let x = $('#TXTCOST').on('keydown', function (event) {
let input_value = $(this).val().toString();
old_val = input_value;
let found_dots = input_value.match(/\./g) || [];
let split_input_value = input_value.split('.');
let prevent_default = false;
// console.log('value = ' + $(this).val());
let tests = [];
tests.push(() => {
return allowed_keys.includes(event.which);
});
tests.push(() => {
return (event.which !== 190) || ((event.which === 190) && (input_value.length > 0) && (found_dots.length === 0))
});
tests.forEach(function (test, index) {
if (test() === false) {
event.preventDefault();
}
});
}).on('input', function (event) {
let input_value = $(this).val().toString();
let tests = [];
tests.push(() => {
if (my_regex.test(input_value)) {
return true;
} else {
return false;
}
});
tests.forEach((test, index) => {
if (test() === false) {
$(this).val(old_val)
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="TXTCOST"/>
try like this.
$('#TXTCOST').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
else{
var input = $(this).val();
if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
event.preventDefault();
}
var arr = (input+String.fromCharCode(event.keyCode)).split('.');
if (arr.length == 1 && parseFloat(arr[0]) > 99999999) {
event.preventDefault();
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="TXTCOST"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="TXTCOST"/>
$('#TXTCOST').keypress(function (event) {
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var input = $(this).val();
if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
event.preventDefault();
}
var arr = input.split('.');
if (arr.length == 1 && parseFloat(arr[0]) >= 99999999) {
event.preventDefault();
}
});
try this
I have the following code to admit decimals:
<input id="precio" type="text" class="form-control" onclick="this.select();" onkeypress="return OnlyDecimal(event, '0.0', 4, 2);"/>
<script>
function OnlyDecimal(e, valInicial, nEntero, nDecimal) {
var obj = e.srcElement || e.target;
var key_code = (document.all) ? e.keyCode : e.which;
var key_val = String.fromCharCode(key_code);
var patron2 = /[\d.]/;
var control = (key_code === 46 && (/[.]/).test(obj.value)) ? false : true;
var existePto = (/[.]/).test(obj.value);
//el tab
if (key_code === 8)
return true;
if (valInicial !== obj.value) {
var TControl = obj.value.length;
if (existePto === false && key_code !== 46) {
if (TControl === nEntero) {
obj.value = obj.value + ".";
}
}
if (existePto === true) {
var subVal = obj.value.substring(obj.value.indexOf(".") + 1, obj.value.length);
if (subVal.length >= nDecimal) {
return false;
}
}
return patron2.test(key_val) && control;
}
else {
if (valInicial === obj.value) {
obj.value = '';
}
return patron2.test(key_val) && control;
}
}
</script>
But when it's at the maximum number of digits allowed and with focus selected, it doesn't allow me to enter numbers to replace the one in the input.
Is there a way to validate this? or how to detect when the input is selected to validate it ?.
The goal is to be able to enter digits in the input when everything is selected. Is there any idea or solution? Is it explained?
you can use selectionStart and selectionEnd like below, if that is what you want
<input id="precio" type="text" class="form-control" onclick="this.select();" onkeypress="return OnlyDecimal(event, '0.0', 4, 2);"/>
<script>
function OnlyDecimal(e, valInicial, nEntero, nDecimal) {
var obj = e.srcElement || e.target;
var key_code = (document.all) ? e.keyCode : e.which;
var key_val = String.fromCharCode(key_code);
var patron2 = /[\d.]/;
var control = (key_code === 46 && (/[.]/).test(obj.value)) ? false : true;
var existePto = (/[.]/).test(obj.value);
var haveSelection = obj.selectionEnd - obj.selectionStart;
//el tab
if (key_code === 8)
return true;
if (valInicial !== obj.value) {
var TControl = obj.value.length;
if (existePto === false && key_code !== 46) {
if (TControl === nEntero) {
obj.value = obj.value + ".";
}
}
if (existePto === true) {
var subVal = obj.value.substring(obj.value.indexOf(".") + 1, obj.value.length);
if (subVal.length >= nDecimal && !haveSelection) {
return false;
}
}
return patron2.test(key_val) && control;
}
else {
if (valInicial === obj.value) {
obj.value = '';
}
return patron2.test(key_val) && control;
}
}
</script>
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);
}
});
In following example I am attempting to change the charCode of the key pressed but it does not change. When I press "a" I want it to type "b". What am I doing wrong?
$("#target").keypress(function(event) {
if ( event.which == 97 ) {
//alert('pressed a');
//event.preventDefault();
event.keyCode = 98;
event.charCode = 98;
event.which = 98;
}
});
You can't override the keycode in the event object...
Look at this snippet:
$('#target').keypress(function(e){
if (e.which == 97)
this.value = this.value + String.fromCharCode(98)
else
this.value = this.value + String.fromCharCode(e.which)
....
return false;
})
replace comma and dash to slash.
$('.pdate').on('keypress', function (e) {
var ch = String.fromCharCode(e.keyCode);
$("div").text(e.keyCode)
if (!((ch >= '0' && ch <= '9') ||
ch == '/' || ch == ',' || ch == '-')) {
return false;
}
if (ch == ',' || ch == '-')
{
var val = $(this).val();
var s = this.selectionStart;
val = val.slice(0, s) + "/" + val.slice(s, val.length);
$(this).val(val)
this.selectionStart = s +1;
this.selectionEnd = s +1;
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" class="pdate" />
<div></div>