Input only with correct numeric - javascript

i wanted to ask how i can combine my regex with the if( ( !regex.test( sybol.... condition, if there is a possibility, and also, how I can shorten my code? without loosing good code view. Also, dash can be only in first place and only one in input, and the same with dot.
$( this ).bind( 'keypress', function( e ){
var code = e.keyCode || e.which;
var symbol = String.fromCharCode( code );
var regex = /[-0-9]|[\b]/;
var currVal = $( this ).val();
var insideInput = currVal.indexOf( '-' );
if( ( !regex.test( symbol ) && code != 37 && code != 39 && code != 46 ) ||
( code == 45 && insideInput == 0 ) || ( currVal.length != 0 && code == 45 ) ) {
e.preventDefault();
}
});

If you want digits only input, you can use following:
$('#test').on('input', function() {
var oldVal = $(this).val();
// remove everything but digits
var newVal = oldVal.replace(/[^\d]/g, '');
// put leading minus back in place (if there was one)
if(oldVal.trim().length > 0 && oldVal.trim()[0] == '-') {
newVal = '-' + newVal;
}
$(this).val(newVal);
});​
See this DEMO.
If you want more, please update your question (describe what are you trying to achieve with your script).

So i combined Michal Klouda ideas and mines and done this function:
$('input').bind('keypress paste', function(e) {
var currVal = $(this).val();
var code = e.keyCode || e.which;
var symbol = String.fromCharCode( code );
var regex = /[0-9\-]|[\b]/;
if(
!regex.test( symbol ) && code != 37 && code != 39 && code != 46 ||
symbol == '%' ||
currVal.length > 0 && currVal[0] == '-' && symbol == '-' ||
currVal.length > 0 && symbol == '.' && currVal.indexOf( '.' ) > -1 ||
currVal.length < 1 && symbol == '.' ||
currVal.length < 2 && symbol == '.' && currVal[0] == '-'
){
e.preventDefault();
}
});
Some explanations:
regex = /[0-9\-]|[\b]/;
Removes all non numeric, exept dash, %, backspace symbols.
Why it isn't removing % symbol, i can't find. ( one more place to inprove code )
code != 37 // leaves left arrow
code != 39 // leaves right arrow
code != 46 // allows to delete code with delete button
symbol == % // prevents from percentage symbol
Other conditions allow you to write one dot and one dash symbol.
Dash allowed only in first place, dot allowed in two conditions: with dash or without.
With dash allowed from 3 position, without from 2 position, but only once. Also it prevents user to paste the code from clipboard.
CODE TESTED:
IE7+
FF
Chrome
Safari
Opera
Try DEMO
P.S: thanks Michal Klouda for help.

Related

jQuery replace comma with dot doesn't work

I have tried to append the code from another post which works perfectly on fiddle on this link: http://jsfiddle.net/WfpEu/51/
The code replaces comma "," as soon as the user types it and turns it to dot "."
$.fn.ForceNumericOnly = function() {
return this.each(function() {
$(this).keydown(function(e) {
if(e.keyCode==188 || e.keyCode==110 || e.keyCode==108){
e.preventDefault();
$(this).val($(this).val() + '.');
}
var key = e.charCode || e.keyCode || 0;
return (key == 8 || key == 9 || key == 46 || key == 110 || key == 188 || key == 190 || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});
});
};
$(".item").ForceNumericOnly();
I have tried to append it to my code here http://jsfiddle.net/p2Hbm/104/ and it doesn't work as it should and i don't know what is wrong. I can't write letters in input fields which is good but also i can't write comma "," it doesn't show up at all.
You need to add the itemclass to your input fields.
Working fiddle: http://jsfiddle.net/p2Hbm/106/

How to allow select-and-typeover on a field that limits characters via keypress listener

I've used a keypress listener to force a field to only accept numbers--and only two numbers at that. The problem is that it prevents the user from typing two numbers, selecting the numbers, and typing over them.
Here's the JavaScript that I used to limit the keypress:
// Only allow 2 numeric characters
jQuery('input').on('keypress', function(e){
console.log( e.which);
// Only allow numbers
var is_number = /[0-9]/.test(String.fromCharCode(e.which));
// Or special characters
var is_special_key = ( e.metaKey || // cmd/ctrl
e.which <= 0 || // arrow keys
e.which == 8 ); // backspace
return ( is_special_key || ( is_number && ($(this).val()).length < 2 ) );
});
Here's a working example: https://jsfiddle.net/pL0ctwka/1/
How can I allow users to select and type over?
Try the code below:
// Only allow 2 numeric characters
jQuery('input').on('keypress', function(e){
console.log( e.which);
// Only allow numbers
var is_number = /[0-9]/.test(String.fromCharCode(e.which));
// Or special characters
var is_special_key = ( e.metaKey || // cmd/ctrl
e.which <= 0 || // arrow keys
e.which == 8 ); // backspace
return ( is_special_key || ( is_number && (( $(this).val( ) ).length < 2 || (this.selectionEnd - this.selectionStart ) ) > 0 ) );
});
https://jsfiddle.net/pL0ctwka/2/

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/

Need to replace "comma" with 'dot'

Please help me to adjust an existing script to replace COMMA with DOT.
I use a script which limit the inserting character into Text fields. Only 1,2,3,4,5,6,7,8,9,0 and "." and "," are accepted to be inserted. I would like to have two buttons of inserting DOT - key==188 (comma) and key== 190 (dot).
jQuery.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 110 ||
key == 188 ||
key == 190 ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
});
};
$("#iMONEY").ForceNumericOnly();
It can be tested HERE
Just use
if(e.keyCode == 188){
e.preventDefault();
$(this).val($(this).val() + '.');
}
Here you go. :)
For future references Mini-Tutorial.
The value of the textbox is updated after keypress event is fired. It's not a place to replace comma with dot. Use keyup event instead:
jQuery.fn.ForceNumericOnly =
function()
{
this.keyup(function(e)
{
// console.log("Change");
$(this).val($(this).val().replace(/,/g,"."));
});
};
$("#iMONEY").ForceNumericOnly();
DEMO
var key = e.charCode || e.keyCode || 0;
// 110 is numpad comma code
if (key === 188 && key === 110) {
e.preventDefault();
$(this).val($(this).val() + '.');
}
You need to use the Replace method
var someVariable = "1,2,3,4,5,6,7,8,9,0";
$mylabel.text( someVariable.replace(',', '.') );
EDIT:
If you are checking from TextBox then do it like this:
if(Key == 188){
var someVariable = $("#TEXTBOXID").val();
somVariable = someVariable.replace(',', '.');
}

How to allow only defined characters as input using jQuery?

How do i allow special characters such as hyphen,comma,slash,space key,backspace key,delete key along with alphanumeric values and restrict the rest in jQuery?
As this criteria(allowed characters/input values) varies from field to field, i would like to make it as a utility method which accepts input field id and allowed characters as parameters.
for example: limitCharacters(textid, pattern)
​You can just check the keyCode on keydown and run preventDefault() if match:
$('input').keydown(function(e) {
if (e.which == 8) { // 8 is backspace
e.preventDefault();
}
});​
http://jsfiddle.net/GVb6L/
If you need to restrict to certain chars AND keyCodes + make it into a jQuery plugin, try something like:
$.fn.restrict = function( chars ) {
return this.keydown(function(e) {
var found = false, i = -1;
while(chars[++i] && !found) {
found = chars[i] == String.fromCharCode(e.which).toLowerCase() ||
chars[i] == e.which;
}
found || e.preventDefault();
});
};
$('input').restrict(['a',8,'b']);​
http://jsfiddle.net/DHCUg/
I did something like this but in jQuery plugin format. This example will only allow numbers and full stops.
You can call this by writing:
$("input").forceNumeric();
And the plugin:
jQuery.fn.forceNumeric = function () {
return this.each(function () {
$(this).keydown(function (e) {
var key = e.which || e.keyCode;
if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
// numbers
key >= 48 && key <= 57 ||
// Numeric keypad
key >= 96 && key <= 105 ||
// comma, period and minus, . on keypad
key == 190 || key == 188 || key == 109 || key == 110 ||
// Backspace and Tab and Enter
key == 8 || key == 9 || key == 13 ||
// Home and End
key == 35 || key == 36 ||
// left and right arrows
key == 37 || key == 39 ||
// Del and Ins
key == 46 || key == 45)
return true;
return false;
});
});
}
I would suggest using David solution for modifier keys like backspace and delete and this code below for characters:
var chars = /[,\/\w]/i; // all valid characters
$('input').keyup(function(e) {
var value = this.value;
var char = value[value.length-1];
if (!chars.test(char)) {
$(this).val(value.substring(0, value.length-1));
}
});
Also, I've experienced some problems with keydown so I'd do it on keyup.
Demo: http://jsfiddle.net/elclanrs/QjVGV/ (try typing a dot . or semicolon ;)

Categories

Resources