allowing input only for float number - javascript

I have pain-time when making input that only allows float number with jquery library. my code can't prevent chacacter "." when it's becoming first input, can anyone guide me to solve this problem?
$('.filterme').keypress(function(eve) {
if ( ( eve.which != 46 || $(this).val().indexOf('.') != -1 )
&& ( eve.which < 48 || eve.which > 57 )
|| ( $(this).val().indexOf('.') == 0)
)
{
eve.preventDefault();
}
});​

I use this - works for keyboard input or copy and paste
$('input.float').on('input', function() {
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="text" class="float" />
Explanation:
First regex replaces anything that's not a number or a decimal.
Second regex removes any instance of a second decimal.

I filter the first position input with the jQuery Caret plugin. Otherwise, once the dot is typed, it's already late to check where it was placed. I tried checking for the dot, then deleting the dot, but it does not look nice.
jQuery caret plugin:
http://examplet.buss.hk/js/jquery.caret.min.js
What I did:
http://jsfiddle.net/FCWrE/422/
Try it :)
$('.filterme').keypress(function(eve) {
if ((eve.which != 46 || $(this).val().indexOf('.') != -1) && (eve.which < 48 || eve.which > 57) || (eve.which == 46 && $(this).caret().start == 0)) {
eve.preventDefault();
}
// this part is when left part of number is deleted and leaves a . in the leftmost position. For example, 33.25, then 33 is deleted
$('.filterme').keyup(function(eve) {
if ($(this).val().indexOf('.') == 0) {
$(this).val($(this).val().substring(1));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/caret/1.0.0/jquery.caret.min.js"></script>
<input type="text" class="filterme">

Regular expression would be my recommendation as well. If the value is being passed as a number and not a string you can use .toString to change it to a string and validate it with regular expression. For example:
var str = value.toString();
if(!str.match(/^-?[0-9]*[.][0-9]+$/)) {
alert("Value must be a float number");
return;
}
return value;
The above regex will match if the value passed is a floating point number. It accepts both negative and positive numbers. If you only want to accept positive numbers simply remove the '-?' from the expression. It will also fail if the value is simply zero '0' without any decimal point. If you want to accept zero simply add it as a condition to the 'if' statement.
You can use the above validation and an onchange event to prevent the user from entering a non-flot number.

Why not using Regular Expression
^[0-9]*[.][0-9]+$
Read code and test here..

You can use the following method, called on onkeypress event. Below is the HTML snippet followed by the JS method:
input type="text" onkeypress="return isNumberKey(event)" id="floor"
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode == 46){
var inputValue = $("#floor").val();
var count = (inputValue.match(/'.'/g) || []).length;
if(count<1){
if (inputValue.indexOf('.') < 1){
return true;
}
return false;
}else{
return false;
}
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)){
return false;
}
return true;
}
Note: The above code also ensures that you enter only single decimal in the input.

Here is my solution, works with negative numbers too (fiddle)
$("input").keypress(function (event) {
var inputCode = event.which;
var currentValue = $(this).val();
if (inputCode > 0 && (inputCode < 48 || inputCode > 57)) {
if (inputCode == 46) {
if (getCursorPosition(this) == 0 && currentValue.charAt(0) == '-') return false;
if (currentValue.match(/[.]/)) return false;
}
else if (inputCode == 45) {
if (currentValue.charAt(0) == '-') return false;
if (getCursorPosition(this) != 0) return false;
}
else if (inputCode == 8) return true;
else return false;
}
else if (inputCode > 0 && (inputCode >= 48 && inputCode <= 57)) {
if (currentValue.charAt(0) == '-' && getCursorPosition(this) == 0) return false;
}
});
function getCursorPosition(element) {
if (element.selectionStart) return element.selectionStart;
else if (document.selection)
{
element.focus();
var r = document.selection.createRange();
if (r == null) return 0;
var re = element.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}

This works for me:
var str = document.getElementById('product_'+id_product).value;
if( !str.match(/^[0-9]*([.,][0-9]+)?$/) ) {
console.log("Value must be a number or float number");
}else{
console.log("The number is valid");
}
I hope this can help someone.
Regards!

Related

Using regex to restrict input in textbox [duplicate]

This question already has answers here:
HTML input that takes only numbers and the + symbol
(7 answers)
Closed 5 years ago.
/^+{0,1}(?:\d\s?){11,13}$/ this regex allows + at first place only and numbers only...
on keypress I want user should only be able to type + at first and digits that what above regex validates But code always goes to if part..why regex not working in this scenario
function ValidatePhone(phone) {
var expr = /^\+?(?:\d\s?){11,13}$/;
return expr.test(phone);
}
var countofPlus = 0;
$("#phone").on("keypress", function (evt) {
if (evt.key == "+")
{
countofPlus = countofPlus + 1;
if (countofPlus > 1 || this.value.length >= 1) {
return false;
}
else return true;
}
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && charCode != 43 && charCode != 32 && charCode != 40 && charCode != 41 && (charCode < 48 || charCode > 57))
return false;
return true;
});
$("#phone").on("keyup", function (evt) {
debugger;
if (evt.key == "+") {
countofPlus--;
return true;
}
});
Adapting an answer from HTML input that takes only numbers and the + symbol to your use-case yields the following (IE-)compatible code:
// Apply filter to all inputs with data-filter:
var inputs = document.querySelectorAll('input[data-filter]');
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
var state = {
value: input.value,
start: input.selectionStart,
end: input.selectionEnd,
pattern: RegExp('^' + input.dataset.filter + '$')
};
input.addEventListener('input', function(event) {
if (state.pattern.test(input.value)) {
state.value = input.value;
} else {
input.value = state.value;
input.setSelectionRange(state.start, state.end);
}
});
input.addEventListener('keydown', function(event) {
state.start = input.selectionStart;
state.end = input.selectionEnd;
});
}
<input id='tel' type='tel' data-filter='\+?\d{0,13}' placeholder='phone number'>
Above code takes copy & pasting, selecting, backspacing etc. into account where your current implementation fails.
Also, I modified the given regex to \+?\d{0,13} so it allows for incomplete input. Use HTML5 form validation to validate the final result.
I think this regex is being applied only to the char code i.e. a string of length 1. In this case regex will always fail.
Instead, try running the regex test on the input value.

JQuery to allow only alphabets, numeric and forward slash in TextBox

I have a text field in ASP.NET and i want to allow only alphanumeric and forward slash (/) keys in that. I tried the following code,
function jsCheckInput(e) {
var evt = (e) ? e : window.event;
var key = (evt.keyCode) ? evt.keyCode : evt.which;
if (key != null) {
key = parseInt(key, 10);
if (key < 47 || (key > 57 && key < 65) || (key > 90 && key < 97) || key > 122) {
if (!jsIsUserFriendlyChar(key)) {
return false;
}
}
else {
if (evt.shiftKey) {
return true;
}
}
}
return true;
}
function jsIsUserFriendlyChar(val) {
// Backspace, Tab, Enter, Insert, and Delete
if (val == 8 || val == 9 || val == 13 || val == 45 || val == 46) {
return true;
}
// Ctrl, Alt, CapsLock, Home, End, and Arrows
if ((val > 16 && val < 21) || (val > 34 && val < 41)) {
return true;
}
return false;
}
In the web forms page i added like below,
<asp:TextBox ID="text_value" CssClass="textbox" onkeydown="return jsCheckInput(event);" runat="server"></asp:TextBox>
Here i am able to enter alphabets and numbers but i am not able to enter the value /. I have enabled the shift key so i can give shift + ? to enter the forward slash. Also another problem is when i press shift + any numeric key the special characters there like ! # # $ % ^ & * ( ) ... are also coming in tet field. What am i doing wrong here?
if you want to use Regular Expression. Ignore if you don't
const regex = /^[a-z0-9\/]+$/gi;
const str = `asdasdas/asdfaASDASDA`; //test string
if(regex.test(str )){
console.log('Allowed'+str);
}
Tested here
You don't need shift key to type forward slash. Key code for forward slash(/) is 191. Just add this also in your if condition.
function jsCheckInput(e) {
var evt = (e) ? e : window.event;
var key = (evt.keyCode) ? evt.keyCode : evt.which;
if (key != null) {
key = parseInt(key, 10);
if (key < 47 || (key > 57 && key < 65) || (key > 90 && key < 97) || key > 122 || key != 191) {
if (!jsIsUserFriendlyChar(key)) {
return false;
}
}
}
return true;
}
SOLUTION
Finally found a solution as below,
function jsCheckInput(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || (charCode > 46 && charCode < 58))
return true;
else if (jsIsUserFriendlyChar(charCode))
return true;
else
return false;
}
catch (err) {
alert(err.Description);
}
}
This code works perfectly!!

Limit numbers before and after decimal point on input number

How to limit numbers for before and after the decimal point, something like 123.123 , so it can have max 3 numbers before . and max 3 numbers after .
<div class="form-group">
<input type="number" class="form-control" name="ta" id="ta" placeholder="ta" ng-model="ta.kol" ng-maxlength="15"/>
<p ng-show="taForm.kol.$error.maxlength" class="help-block">Max 15 symbols !</p>
</div>
You can add a onchange event on the input field and call a function that validates the current input value using regex and communicate same to the user.
Regex : ^[0-9]{0,3}.?[0-9]{0,3}$
JS Code to validate:
function validateNumberInput(inputNumber){
return number.search(/^[0-9]{0,3}.?[0-9]{0,3}$/) == 0 ? true : false;
}
Also you can write a directive in angular that can handle the same.
This can be solved with a simple piece of javascript if you just add an Event Listener to the input and then split the input on the decimal point you can then check the length of both parts and act accordingly.
https://jsfiddle.net/pk07net6/
function checkNumbers()
{
console.log(this.value);
var numbers = this.value.split('.');
var preDecimal = numbers[0];
var postDecimal = numbers[1];
if (preDecimal.length>3 || postDecimal.length>3)
{
alert("Max 3 numbers before and after the decimal point.")
this.select();
}
}
//ADD LISTENER TO INPUT
var input = document.getElementById("numberInput");
console.log(input);
input.addEventListener("change", checkNumbers)
You can use ng-pattern with a regex:
<input ng-pattern="/^[0-9]{1,3}(\.\d{0,3})?/" />
docs: https://docs.angularjs.org/api/ng/directive/ngPattern
For the fraction its pretty easy as you can use Angular number filter. As for the number before the digit you should create a filter like this :
app.filter('beforeDigit', function ($filter) {
return function (input) {
if (input>1000)
return (input % 1000)
elseif(input<1000)
return input;
};
});
So in the end you will end up with something like this :
{{val | filter:{number:3}, filter:beforeDigit }}
After hours of work, I create java-script function which work on keypress event. Number can be 8 characters before decimal separator and 2 character after decimal separator.
https://codepen.io/dumbelovic/pen/bvdXXq
function BeforeAfter(e, obj) {
sepDec = "."
var keycode;
var fieldval = obj.value;
if (window.event) keycode = window.event.keyCode;
else if (e) { keycode = e.which; }
else { return true; }
// denided first charatcter to be zero
if (fieldval == "" && keycode == 48)
return false;
// denided first character to be decimal point
if (fieldval == "" && (keycode == 44 || keycode == 46))
return false;
// enter first decimal point,
// but every next try to eneter decimal point return false
if (fieldval != "" && ((keycode == 44 || keycode == 46))) {
if (fieldval.indexOf(sepDec) < 0) {
var newValue = fieldval + sepDec;
$(obj).val(newValue);
}
return false;
}
var splitfield = fieldval.split(sepDec);
var beforeDecimalPoint;
var afterDecimalPoint;
if (splitfield.length == 1) {
beforeDecimalPoint = splitfield[0];
afterDecimalPoint = "";
}
else if (splitfield.length == 2) {
beforeDecimalPoint = splitfield[0];
afterDecimalPoint = splitfield[1];
}
if (beforeDecimalPoint.length == 8 && keycode != 8 && keycode != 0) {
if (obj.selectionStart >= 0 && obj.selectionStart <= 8)
return false;
}
if (afterDecimalPoint.length == 2 && keycode != 8 && keycode != 0) {
if (obj.selectionStart >= beforeDecimalPoint.length + 1 && obj.selectionStart <= beforeDecimalPoint.length + 1 + 2)
return false;
}
return true;
}

javascript to allow only negative and positive numbers and decimal upto 6 digits on keypress

I need to validate a textbox in my cshtml page to accept only negative or positive numbers and upto 6 decimal places. This is what I have tried so far.
function AcceptUptoSixDecimalPlacesWithNegative(event, elem) {
if ((event.which != 46 || $(elem).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
if (event.keyCode !== 8 && event.keyCode !== 46 && event.keyCode !== 9 && event.keyCode !== 0 && event.keyCode !== 45) { //exception
event.preventDefault();
}
}
var text = $(elem).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 6)) {
if (event.keyCode !== 8 && event.keyCode !== 46 && event.keyCode !== 9) { //exception
event.preventDefault();
}
}
This is helping me achieve six digits after decimal point but then it allows all special characters and alphabets too.
Any help with this problem would be appreciated.
Thanks.
You could check the value with Regex:
var re = /^-?\d*\.?\d{0,6}$/;
var text = $(elem).val();
var isValid = (text.match(re) !== null);
The Regex means:
^ : beginning of string
-? : one or zero "-"
\d* : 0 to infinite numbers
\.? : 0 or 1 "."
\d{0,6} : from 0 to 6 numbers
$ : End of string
You could use the isNaN() function of JavaScript.
var inputPrevValue = "";
$(document).ready(function () {
$("#numbersOnly").change(function () {
if (isNaN($(this).val()) || $(this).val().length > 6) {
$(this).val(inputPrevValue);
} else {
inputPrevValue = $(this).val();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="numbersOnly">
This is a (very simplistic) example that tests if the input is a number less than 6 characters in length. If not, it'll revert it to the last acceptable value.
***Adding Comment as no access yet!!!
Try Regex "^[0-9]+(.[0-9]{1,2})?$" to verify the text and then proceed with logic.
js code:
var patt = new RegExp("^[0-9]+(.[0-9]{1,6})?$");
var res = patt.test(str);
if res is true then proceed else return false;
Here are a list of functions to help in your question:
Math.sign() checks if its a positive/0, negative/0 and NaN
Number MDN contains a list of number functions
parseFloat()
count digits after decimal post or regex ie. \d+([.\d{1,6}]*)\
In your context, a combination of validations in the following example:
let x = elem;
if(Math.sign(x) === 1 || Math.sign(x) === -1) && ...
// decimal validations
Hope this helps.
Don't validate the keys pressed. There are many ways to change input
value. Handle the oninput event.
You may treat the value as a string and validate using a
regular expression, but I think it's better to combine string and number-related
functions
For example:
<input type="number" step="any" oninput="validate(this)" />
function validate(input){
var number = parseFloat(input.value);
if( number == input.value && input.value.length <= number.toFixed(6).length ){ /* valid! */ }
}
http://jsfiddle.net/tto2yvwj/

Restrict to 2 decimal places in keypress of a text box?

I want to enter a decimal point in a text box. I want to restrict the user by entering more than 2 digits after the decimal point. I have written the code for achieving that in the Keypress event.
function validateFloatKeyPress(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
if (charCode == 46 && el.value.indexOf(".") !== -1) {
return false;
}
if (el.value.indexOf(".") !== -1)
{
var range = document.selection.createRange();
if (range.text != ""){
}
else
{
var number = el.value.split('.');
if (number.length == 2 && number[1].length > 1)
return false;
}
}
return true;
}
<asp:TextBox ID="txtTeamSizeCount" runat="server" onkeypress="return validateFloatKeyPress(this,event);" Width="100px" MaxLength="6"></asp:TextBox>
The code is working but the issue is: if I enter ".75" and then change it to "1.75", it is not possible. Only way to do it is delete it completely and then type "1.75". This issue occurs if there are already 2 digits after decimal in the textbox. The conditions that I impose are
a) After decimal is present, it must at least have 1 or 2 digits. For ex .75 or .7 or 10.75 or 333.55 or 333.2 is accepted. but not .753 or 12.3335
b) Before the decimal, it not a must for the user to enter a value. User must also be able to enter integer numbers also.
Can you tell me what could be the issue?
Thanks,
Jollyguy
You were almost there. Just check that there are no more than 2 characters after the decimal.
UPDATE 1 - check carat position to allow character insertion before the decimal.
UPDATE 2 - correct issue pointed out by ddlab's comment and only allow one dot.
function validateFloatKeyPress(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
//just one dot (thanks ddlab)
if(number.length>1 && charCode == 46){
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(".");
if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
return false;
}
return true;
}
//thanks: http://javascript.nwbox.com/cursor_position/
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', o.value.length)
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text)
} else return o.selectionStart
}
http://jsfiddle.net/S9G8C/1/
http://jsfiddle.net/S9G8C/203/
Consider leveraging HTML5's Constraint Validation API. It doesn't necessarily prevent typing invalid values, but the field is marked invalid and it halts submission of the <form> (by default). I added the <output> to illustrate why the browser considers e.g. "1.100" a valid value (it sees the numeric value as "1.1").
<input id="n" type="number" step=".01">
var
n = document.getElementById('n'),
o = document.getElementById('o'),
didInputN = function(e) {
o.value = n.valueAsNumber;
};
n.addEventListener('input', didInputN);
input:invalid {
color: white;
background-color: red;
}
<input id="n" type="number" step=".01">
<output id="o" for="n"></output>
Philosophically, you might consider this a more usable approach as it allows the user to paste an invalid entry and edit it directly in the field.
You can do it by another way with onchange event, to not restrict to user to type, rather just convert number after typing, to make uniform, like this,
function validateFloatKeyPress(el) {
var v = parseFloat(el.value);
el.value = (isNaN(v)) ? '' : v.toFixed(2);
}
<input id="aninput" type="text" onchange="validateFloatKeyPress(this);" />
45.846 should be 45.85 but in your code user needed to convert their-self and then they will type 45.85 directly
1.)No multiple decimals points.
2.)Two numbers after decimal point.
3.)Allow only Numbers and one decimal point(.).
This will help.jsFiddle
function decimalValidation(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split('.');
if(charCode == 8) {
return true;
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
//just one dot
if(number.length>1 && charCode == 46){
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(".");
if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
return false;
}
return true;
}
function getSelectionStart(o) {
return o.selectionStart
}
Hi #webvitaly The above code will work in IE too please check
And backspace after decimals not working in Mozilla i updated my answer.
this code is very complet, I change "." to ",":
can't "," in begin
can't write more ","
<script type="text/javascript">
function isNumberKey(evt, el) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split(',');
var caracter = el.value;
if (charCode != 44 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
if (charCode == 44 && caracter == "") {
return false;
}
if (charCode == 44 && caracter.indexOf(",") != -1) {
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(",");
if (caratPos > dotPos && dotPos > -1 && (number[1].length > 1)) {
return false;
}
return true;
}
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', o.value.length)
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text)
} else return o.selectionStart
}
</script>
My problem was that I need it to show an error message in real time if the user is allowed only 2 decimals:
value = parseFloat(valueFromInput);
parseFloat(value.toFixed(2)) !== value // condition to check
The above code worked for me..toFixed converts the float to a string wit only 2 decimals and I have to convert back to float to check with the initial value if are the same.
P.S. And before this condition you should check if the value is NaN.

Categories

Resources