Allow only numbers and dot in script - javascript

Am using this javascript for restrict users to type only numbers and only one dot as decimal separator.
<script type="text/javascript">
function fun_AllowOnlyAmountAndDot(txt)
{
if(event.keyCode > 47 && event.keyCode < 58 || event.keyCode == 46)
{
var txtbx=document.getElementById(txt);
var amount = document.getElementById(txt).value;
var present=0;
var count=0;
if(amount.indexOf(".",present)||amount.indexOf(".",present+1));
{
// alert('0');
}
/*if(amount.length==2)
{
if(event.keyCode != 46)
return false;
}*/
do
{
present=amount.indexOf(".",present);
if(present!=-1)
{
count++;
present++;
}
}
while(present!=-1);
if(present==-1 && amount.length==0 && event.keyCode == 46)
{
event.keyCode=0;
//alert("Wrong position of decimal point not allowed !!");
return false;
}
if(count>=1 && event.keyCode == 46)
{
event.keyCode=0;
//alert("Only one decimal point is allowed !!");
return false;
}
if(count==1)
{
var lastdigits=amount.substring(amount.indexOf(".")+1,amount.length);
if(lastdigits.length>=2)
{
//alert("Two decimal places only allowed");
event.keyCode=0;
return false;
}
}
return true;
}
else
{
event.keyCode=0;
//alert("Only Numbers with dot allowed !!");
return false;
}
}
</script>
<td align="right">
<asp:TextBox ID="txtQ1gTarget" runat="server" Width="30px" CssClass="txtbx" MaxLength="6" onkeypress="return fun_AllowOnlyAmountAndDot(this);"></asp:TextBox>
</td>
But the onkeypress(this) event returns object required error in that function at this place
var amount = document.getElementById(txt).value;
What's my mistake here?

This is a great place to use regular expressions.
By using a regular expression, you can replace all that code with just one line.
You can use the following regex to validate your requirements:
[0-9]*\.?[0-9]*
In other words: zero or more numeric characters, followed by zero or one period(s), followed by zero or more numeric characters.
You can replace your code with this:
function validate(s) {
var rgx = /^[0-9]*\.?[0-9]*$/;
return s.match(rgx);
}
That code can replace your entire function!
Note that you have to escape the period with a backslash (otherwise it stands for 'any character').
For more reading on using regular expressions with javascript, check this out:
http://www.regular-expressions.info/javascript.html
You can also test the above regex here:
http://www.regular-expressions.info/javascriptexample.html
Explanation of the regex used above:
The brackets mean "any character inside these brackets." You can use a hyphen (like above) to indicate a range of chars.
The * means "zero or more of the previous expression."
[0-9]* means "zero or more numbers"
The backslash is used as an escape character for the period, because period usually stands for "any character."
The ? means "zero or one of the previous character."
The ^ represents the beginning of a string.
The $ represents the end of a string.
Starting the regex with ^ and ending it with $ ensures that the entire string adheres to the regex pattern.
Hope this helps!

Use Jquery instead. Add a decimal class to your textbox:
<input type="text" class="decimal" value="" />
Use this code in your JS. It checks for multiple decimals and also restrict users to type only numbers.
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9\.]/g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});​
Check this fiddle: http://jsfiddle.net/2YW8g/
Hope it helps.

Just add the code below in your input text:
onkeypress='return event.charCode == 46 || (event.charCode >= 48 && event.charCode <= 57)'

Instead of using this:
onkeypress="return fun_AllowOnlyAmountAndDot(this);"
You should use this:
onkeypress="return fun_AllowOnlyAmountAndDot(this.id);"

function isNumberKey(evt,id)
{
try{
var charCode = (evt.which) ? evt.which : event.keyCode;
if(charCode==46){
var txt=document.getElementById(id).value;
if(!(txt.indexOf(".") > -1)){
return true;
}
}
if (charCode > 31 && (charCode < 48 || charCode > 57) )
return false;
return true;
}catch(w){
alert(w);
}
}
<html>
<head>
</head>
<body>
<INPUT id="txtChar" onkeypress="return isNumberKey(event,this.id)" type="text" name="txtChar">
</body>
</html>

<input type="text" class="decimal" value="" />
$('.decimal').keypress(function(evt){
return (/^[0-9]*\.?[0-9]*$/).test($(this).val()+evt.key);
});
I think this simple solution may be.

This works best for me.
I also apply a currency formatter on blur where the decimal part is rounded at 2 digits just in case after validating with parseFloat.
The functions that get and set the cursor position are from Vishal Monpara's blog. I also do some nice stuff on focus with those functions. You can easily remove 2 blocks of code where 2 decimals are forced if you want and get rid of the set/get caret functions.
<html>
<body>
<input type="text" size="30" maxlength="30" onkeypress="return numericValidation(this,event);" />
<script language="JavaScript">
function numericValidation(obj,evt) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
if (charCode == 46) { //one dot
if (obj.value.indexOf(".") > -1)
return false;
else {
//---if the dot is positioned in the middle give the user a surprise, remember: just 2 decimals allowed
var idx = doGetCaretPosition(obj);
var part1 = obj.value.substr(0,idx),
part2 = obj.value.substring(idx);
if (part2.length > 2) {
obj.value = part1 + "." + part2.substr(0,2);
setCaretPosition(obj, idx + 1);
return false;
}//---
//allow one dot if not cheating
return true;
}
}
else if (charCode > 31 && (charCode < 48 || charCode > 57)) { //just numbers
return false;
}
//---just 2 decimals stubborn!
var arr = obj.value.split(".") , pos = doGetCaretPosition(obj);
if (arr.length == 2 && pos > arr[0].length && arr[1].length == 2)
return false;
//---
//ok it's a number
return true;
}
function doGetCaretPosition (ctrl) {
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
function setCaretPosition(ctrl, pos){
if(ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
</script>
</body>
</html>

function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 46 || charCode > 57)) {
return false;
}
return true;
}
you should use this function and write the properties of this element ;
HTML Code:
<input id="deneme" data-mini="true" onKeyPress="return isNumber(event)" type="text"/>`

try This Code
var check = function(evt){
var data = document.getElementById('num').value;
if((evt.charCode>= 48 && evt.charCode <= 57) || evt.charCode== 46 ||evt.charCode == 0){
if(data.indexOf('.') > -1){
if(evt.charCode== 46)
evt.preventDefault();
}
}else
evt.preventDefault();
};
document.getElementById('num').addEventListener('keypress',check);
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type="text" id="num" value="" />
</body>
</html>

<script type="text/javascript">
function numericValidation(txtvalue) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
if (!(document.getElementById(txtvalue.id).value))
{
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
else {
var val = document.getElementById(txtvalue.id).value;
if(charCode==46 || (charCode > 31 && (charCode > 47 && charCode < 58)) )
{
var points = 0;
points = val.indexOf(".", points);
if (points >= 1 && charCode == 46)
{
return false;
}
if (points == 1)
{
var lastdigits = val.substring(val.indexOf(".") + 1, val.length);
if (lastdigits.length >= 2)
{
alert("Two decimal places only allowed");
return false;
}
}
return true;
}
else {
alert("Only Numarics allowed");
return false;
}
}
}
</script>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtHDLLevel" MaxLength="6" runat="server" Width="33px" onkeypress="return numericValidation(this);" />
</div>
</form>

You can use this
Javascript
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)&&(charCode!=46)) {
return false;
}
return true;
}
Usage
<input onkeypress="return isNumber(event)" class="form-control">

This function will prevent entry of anything other than numbers and a single dot.
function validateQty(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode != 45 && charCode != 8 && (charCode != 46) && (charCode < 48 || charCode > 57))
return false;
if (charCode == 46) {
if ((el.value) && (el.value.indexOf('.') >= 0))
return false;
else
return true;
}
return true;
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = evt.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
};
<input type="text" onkeypress='return validateQty(this,event);'>

Try this for multiple text fileds (using class selector):
Click here for example..
var checking = function(event){
var data = this.value;
if((event.charCode>= 48 && event.charCode <= 57) || event.charCode== 46 ||event.charCode == 0){
if(data.indexOf('.') > -1){
if(event.charCode== 46)
event.preventDefault();
}
}else
event.preventDefault();
};
function addListener(list){
for(var i=0;i<list.length;i++){
list[i].addEventListener('keypress',checking);
}
}
var classList = document.getElementsByClassName('number');
addListener(classList);
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type="text" class="number" value="" /><br><br>
<input type="text" class="number" value="" /><br><br>
<input type="text" class="number" value="" /><br><br>
<input type="text" class="number" value="" /><br><br>
</body>
</html>

<script type="text/Javascript">
function checkDecimal(inputVal) {
var ex = /^[0-9]+\.?[0-9]*$/;
if (ex.test(inputVal.value) == false) {
inputVal.value = inputVal.value.substring(0, inputVal.value.length - 1);
}
}
</script>

In this function there is an error while editing it when I have added 2 digits(I have defined it's limit 2) after decimal point than it returns false, like if we have to change 1486.00 to 1582.00 without clearing the whole input or deleting any number after decimal point it will return false.
There is a small change required, where the condition of count is 1(count === 1) there add a condition event.target.selectionStart > amount.indexOf(".")
The final code will be
const validDecimal = (event) => {
if ((event.charCode > 47 && event.charCode < 58) || event.charCode === 46) {
var amount = event.target.value;
var present = 0;
var count = 0;
do {
present = amount.indexOf(".", present);
if (present != -1) {
count++;
present++;
}
} while (present != -1);
if (present === -1 && amount.length === 0 && event.charCode === 46) {
event.charCode = 0;
// alert("Wrong position of decimal point not allowed !!");
return false;
}
if (count >= 1 && event.charCode === 46) {
event.charCode = 0;
// alert("Only one decimal point is allowed !!");
return false;
}
if (count === 1 && event.target.selectionStart > amount.indexOf(".")) {
var lastdigits = amount.substring(
amount.indexOf(".") + 1,
amount.length
);
if (lastdigits.length >= 2) {
// alert("Two decimal places only allowed");
event.charCode = 0;
return false;
}
}
return true;
} else {
event.charCode = 0;
// alert("Only Numbers with dot allowed !!");
return false;
}
};

Please try below code. this could help you to solve it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script>
function fnAllowNumbersAndDotKey(input, event)
{
var charCode = (event.which) ? event.which : event.keyCode;
if (charCode == 46)
{
//only one dot (.) allow
if (input.value.indexOf('.') === -1)
{
return true;
}
else
{
return false;
}
}
else
{
if (charCode > 31 && (charCode < 48 || charCode > 57))
{
return false;
}
}
return true;
}
</script>
</head>
<body>
<form method='post' >
<input type="text" name='amount' class='form-control' onkeypress="return fnAllowNumbersAndDotKey(this, event);" maxlength="50" />
</form>
</body>
</html>

<input type="text" class="form-control" id="odometer_reading" name="odometer_reading" placeholder="Odometer Reading" onblur="odometer_reading1();" onkeypress='validate(event)' required="" />
<script>
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
</script>

Hope this could help someone
$(document).on("input", ".numeric", function() {
this.value = this.value.match(/^\d+\.?\d{0,2}/);});

Related

Limit textbox to 10 digits with and also with allowed decimals in jquery

I've been stuck on a problem and searching for it, but couldn't find one.
I have a text field where I want to allow 10 digits and decimal values, for example my allowed digits would be:
1.11
1234567890
Anything within 10 digit range (have problems in these cases below)
12345678.13
123456789.05
1234567890.12
I can already restrict textbox to 10 digits but the question is how to allow only 2 decimals after 10 digits.
My code is:
function CheckNumber(textBoxValue,evt){
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 8 || charCode == 37) {
return true;
} else if (charCode == 46 && textBoxValue.indexOf('.') != -1) {
return false;
} else if (charCode > 31 && charCode != 46 && (charCode < 48 || charCode > 57)) {
return false;
}
console.log(charCode);
if(textBoxValue.length){
newVal = textBoxValue.split('.');
console.log(newVal);
if(newVal[0].length > 9){
if(charCode == 46){
return true;
}
return false;
}
}
return true;
}
Uhhmm, why not use regex for this? Here is a working fiddle:
https://jsfiddle.net/L18d0qut/3/
EDIT:
I changed the code accordingly. Is this fiddle working for you?
I modified the checks to meet your criteria. The key code is now this:
$('#input').on('keyup', function(){
var value = $(this).val();
if(value.match(/^[0-9,.]*$/)) {
if(value.indexOf(".") >= 0 || value.indexOf(",") >= 0){
console.log("YAY, we have a float, so it is valid!");
} else if(value.length <= 10) {
console.log("Valid!");
} else {
console.log("invalid!");
}
} else {
console.log("Only numbers and . or , are allowed!");
}
});
NOTE: This works for floating numbers with . and also with ,. If you do not want this you can simply modify to your needs in the regex and indexOf() methods.
I check the length of the input AND check for the contents by regex. Is this what you're looking for?
Just have a look in the console for the result :-).
I have modified your code & created something like this.
function CheckNumber(textBoxValue,evt){
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 8 || charCode == 37) {
return true;
} else if (charCode == 46 && textBoxValue.indexOf('.') != -1) {
return false;
} else if (charCode > 31 && charCode != 46 && (charCode < 48 || charCode > 57)) {
return false;
}
//console.log(charCode);
if(textBoxValue.length){
newVal = textBoxValue.split('.');
/*console.log(newVal[1]);*/
if(typeof(newVal[1])!='undefined'){
if(newVal[1].length !=2){
return true;
}else{
return false;
}
}
if(newVal[0].length > 9){
if(charCode == 46){
return true;
}
if((charCode >= 48 || charCode <=57) && newVal[0].length == 10 && textBoxValue.indexOf('.') != -1 ){
if(newVal[1].length !=2){
return true;
}else{
return false;
}
}
return false;
}
}
return true;
}
You can check
if(newVal[1].length > 2){
// your code
}
Try this..............
function CheckNumber(textBoxValue,evt){
var a = textBoxValue.replace('.', '');
if(a.length <= 10){
console.log("valid");
} else {
console.log("invalid");
}
}
Try this:
function IsValid(input) {
return (/^\d{0,10}(\.\d{0,2})?$/).test(input);
}
This allows 10 digits and 2 (optional) decimals. Input must be string.
This code allow you only two decimal digits and 10 number before decimal point
/^\d {0,12} (.\d{0,2})?$/;
you can set your textbox length by {0,12} where 0 : min length and 12 : max length
function IsValidNumber(Number) {
var expr = /^\d{0,12}(\.\d{0,2})?$/;
return expr.test(Number);
};
function ValidateNumber() {
var Number = document.getElementById("txtNumber").value;
if (!IsValidNumber(Number)) {
alert("Invalid number");
}
else {
alert("Valid number.");
}
}
<input type="text" id="txtNumber" />
<input type="button" id="btnValidate" value="Validate" onclick = "ValidateNumber()" />
Have you considered textbox input pattern using regex?
Something like pattern="\d{10}\.\d{2}$"

How to disAllow minus (-) in text box

Here I have a function which only allows numeric and percentage. But it is allowing minus(-), I want to restrict that minus in that script. How can I restrict.Here is my script.Or please suggest me a dirctive for this.
function validateQty(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode != 45 && charCode != 8 && charCode != 37 && (charCode != 46) && (charCode < 48 || charCode > 57))
return false;
if (charCode == 46) {
if ((el.value) && (el.value.indexOf('.') >= 0))
return false;
else
return true;
}
return true;
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = evt.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
};
You can allow what you want to be as input. Do something like this.
function restrictInput(el) {
el.addEventListener('input', function(e) {
if (!e.target.value.match(/^\d+$|%$/)) {
e.target.value = e.target.value.slice(0, -1)
}
console.log(e.target.value);
})
}
restrictInput(document.getElementById("input1"));
restrictInput(document.getElementById("input2"));
<input id="input1">
<input id="input2">
updated: As asked by OP. A generic function to handle inputs.
NOTE: You can add more restrictions as you want inside this function
You could use input=number
<input type="number" min="0" />
Using javascript you could do:
// Select your input element.
var numInput = document.querySelector('input');
// Listen for input event on numInput.
numInput.addEventListener('input', function () {
// Let's match only digits.
var num = this.value.match(/^\d+$/);
if (num === null) {
// If we have no match, value will be empty.
this.value = "";
}
}, false)
If the data from the input field will be sent to the server, make sure to add this validation on the server too.
I think you can simplify your script by just testing it against a regular expression.
So your function would essentially change to something like this
function validateQty(el, evt)
{
var regex = new RegExp(/^\d+$|%$/);
return regex.test(el.value);
};
JSFiddle

textbox validation for two numbers and two decimal values in asp.net with javascript

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

Textbox only allow floating point number

Here is the code in html to allow only one decimal point in a textbox:
<html>
<head>
<script type="text/javascript" language="javascript">
function isNumberKey(evt) {
var charCode = (evt.charCode) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
else {
var input = document.getElementById("txtChar").value;
var len = document.getElementById("txtChar").value.length;
var index = document.getElementById("txtChar").value.indexOf('.');
if (index > 0 && charCode == 46) {
return false;
}
if (index >0 || index==0) {
var CharAfterdot = (len + 1) - index;
if (CharAfterdot > 2) {
return false;
}
}
if (charCode == 46 && input.split('.').length >1) {
return false;
}
}
return true;
}
</script>
</head>
<body>
<input type="text" id="txtChar" onkeypress="return isNumberKey(event)" name="txtChar" class="CsstxtChar" maxlength="4"/>
</body>
</html>
I want to done this in asp.net using c#.This code is not properly working in asp.net.
use this it would be helpful....
$('.urInputField').keyup(function(e){
var val = $(this).val();
var regexTest = /^\d{0,8}(\.\d{1,2})?$/;
var ok = regexTest.test(val);
if(ok) {
$(this).css('background-color', 'green');
} else {
$(this).css('background-color', 'red');
}
});
the id of controls may differ from what you enter in asp.net source for example when you use parent-child controls or use master pages... , So, you can not use document.getElementById simply.
as i see your code is not just to block non-digit keys as other ones suggest duplicate solutions, but it also block backspace or arrow keys and put a limit on number of digits after decimal point such that only one digit is allowed after dot. i don't change these custom algorithm you used in your code.
this code get the source element which causes the keypress from event parameters:
<script type="text/javascript" language="javascript">
function isNumberKey(event) {
var e = event || window.event;
var src = e.srcElement || e.target;
var charCode = e.which || e.keyCode || e.charCode;
//document.getElementById("label").value = src.id; //just for test/debug
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
else
{
var input = src.value;
var len = input.length;
var index = input.indexOf('.');
if (index > 0 && charCode == 46) return false;
if (index > 0 || index == 0) {
var CharAfterdot = (len + 1) - index;
if (CharAfterdot > 2) return false;
}
if (charCode == 46 && input.split('.').length > 1) {
return false;
}
}
return true;
}
</script>
Use this Source will work good for float numbers
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
thanks Vamsi

Allowing only numbers and one decimal

Guys and gals i have this piece of JavaScript code that only allows for numbers and one decimal period. The problem i'm having is that when i tab over to my textbox controls it highlights the value but i have press backspace to erase then enter a number. That is an extra keystroke that i want to prevent.
Props to the guy who created it found (http://www.coderanch.com/t/114528/HTML-CSS-JavaScript/decimal-point-restriction) and here is the code. I put this on keyUp event.
<script>
// Retrieve last key pressed. Works in IE and Netscape.
// Returns the numeric key code for the key pressed.
function getKey(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
function restrictChars(e, obj)
{
var CHAR_AFTER_DP = 2; // number of decimal places
var validList = "0123456789."; // allowed characters in field
var key, keyChar;
key = getKey(e);
if (key == null) return true;
// control keys
// null, backspace, tab, carriage return, escape
if ( key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
// get character
keyChar = String.fromCharCode(key);
// check valid characters
if (validList.indexOf(keyChar) != -1)
{
// check for existing decimal point
var dp = 0;
if( (dp = obj.value.indexOf( ".")) > -1)
{
if( keyChar == ".")
return false; // only one allowed
else
{
// room for more after decimal point?
if( obj.value.length - dp <= CHAR_AFTER_DP)
return true;
}
}
else return true;
}
// not a valid character
return false;
}
</script>
<input type="text" class="decimal" value="" />
And in Js use this
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9\.]/g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
Check this fiddle: http://jsfiddle.net/2YW8g/
THis worked for me, i have taken this answer from "Nickalchemist" and take none of its credit.
If you can't use an already stable and well-know library, you can try something like this:
document.write('<input id="inputField" onkeyup="run(this)" />');
function run(field) {
setTimeout(function() {
var regex = /\d*\.?\d?/g;
field.value = regex.exec(field.value);
}, 0);
}
I know it doesn't prevent the wrong char to appear, but it works.
PS: that setTimeout(..., 0) is a trick to execute the function after the value of the field has already been modified.
Here is a sample solution that will accept a number with one(1) decimal point only. e.g 1.12, 11.5
Enter a number with one(1) decimal point only<br />
<input type="text" id="decimalPt"> <br />
$('.decimalPt').keypress(function(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 8 || charCode == 37) {
return true;
} else if (charCode == 46 && $(this).val().indexOf('.') != -1) {
return false;
} else if (charCode > 31 && charCode != 46 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
});
Take a look at this: https://jsfiddle.net/sudogem/h43r6g7v/12/
I think it would be best to use something that already exists... like Masked Input Plugin with jQuery
Try this,
$('input').on('keydown', function (event) {
return isNumber(event, this);
});
function isNumber(evt, element) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode != 190 || $(element).val().indexOf('.') != -1) // “.” CHECK DOT, AND ONLY ONE.
&& (charCode != 110 || $(element).val().indexOf('.') != -1) // “.” CHECK DOT, AND ONLY ONE.
&& ((charCode < 48 && charCode != 8)
|| (charCode > 57 && charCode < 96)
|| charCode > 105))
return false;
return true;
}
Be sure to test on any browser. The accepted answer doesn't work on Firefox.
Try HTML5 type number:
<input type="number" placeholder="1.0" step="0.1">
You could define min="0" max="10"
Reference:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#Controlling_input_size
Note: type="number" is not supported in Internet Explorer 9 and earlier versions.
I solve my problem with like this.
const sanitize = (value = '') => value.replace(/(-(?!\d))|[^0-9|-]/g, '') || ''
export const toNumeric = value => {
let digits = sanitize(value)
// parseInt with 0 fix/avoid NaN
digits = parseInt(0 + digits)
let newValue = digits.toString().padStart(4, 0)
return newValue
}

Categories