Accept only numbers and tab in inputs javascript - javascript

I have some text fields and I want the user to write only numbers and also TAB to go to other inputs easily. I have this javascript code:
function validateNumbers(event) {
if(event.charCode >= 48 && event.charCode <= 57){
return true;
}
return false;
}
And in the HTML I use the attribute onkeypress to call the function.
Could you help me with my code to also accept the TAB key please?

be careful this codes was not working in mobile browsers.
$(document).ready(function() {
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// 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();
}
});
});

You can use tabindex="1" property in your input tag to specify which input it needs to be focused next using numbers like 1,2 etc.
Here is an example based on your code

Instead of keypress, handle keydown and remove all non-numeric values
var input = document.querySelectorAll( "input" );
Array.from( input ).forEach( function( el ){
el.addEventListener( "keyup", validateNumbers );
});
function validateNumbers(event)
{
var inputObj = event.currentTarget;
inputObj.value = inputObj.value.replace(/[^0-9]/g, "");
}
<input/>
<input/>

Related

Phone Number Jquery validation ... need numbers AND a few other characters

Someone helped me create a jquery contact form, with field validation. There is a phone number field. The field allows for only numbers. We need the field to also contain a few other common "phone" character... such as ()-. and space. Can someone help me modify the code below ...
// only numberic value validation
$( ".only_numberic" ).keypress(function(event){
var inputValue = window.event ? event.keyCode : event.which;
// allow letters and whitespaces only.
if( !( inputValue >= 48 && inputValue <= 57) && (inputValue != 0 && inputValue != 8 && inputValue != 9 ) ) {
event.preventDefault();
}
});
Note: I don't mind that the class is still "only_numberic" (that's only a name) ... just need the validation fixed.
FINAL FIX
Below is the final fix that works.
// only numberic value validation
$( ".only_numberic" ).keypress(function(event){
var inputValue = window.event ? event.keyCode : event.which;
// allow letters and whitespaces only, and () and - and period[.] and (space).
if( !( inputValue >= 48 && inputValue <= 57) && (inputValue != 0 && inputValue != 8 && inputValue != 9 && inputValue!=40 && inputValue!=41 && inputValue!=45 && inputValue!=46 && inputValue!=32) ) {
event.preventDefault();
}
});
Here is the code for that. Copy this function and add "number-input" class to your textbox. It accepts only number and space. You can add more characters by adding ASCII value into this array:
[32,46, 8, 9, 27, 13, 110, 190]
Phone Number: <input type="text" class="number-input">
$(document).on('keydown','.number-input',function(e){
console.log(e.keyCode);
if ($.inArray(e.keyCode, [32,46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// 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();
}
});
$(document).ready( function (){ $( "#mobile-num" ).on( "blur" , functi
var mobNum = $( this ).val();
var filter = /^\d*(?:\.\d{1,
if (filter.test(mobNum)) {
if (mobNum.length!= 10 ){
alert( "valid" );
} else {
alert( 'Please put 10
return false;
}
}
else {
alert("not a vaild number");
return false;
} });
});

How to prevent all special characters in a form

So I am trying to prevent all special characters in a form. I want only numbers and alphabet characters. For some reason my javascript below is always shows special characters event if I have only "232 elm".
I also want to use a period or exlamation point. Mainly I am trying to prevent these ¡™£¢∞§¶•ªº. We have users that like to use the degree symbol instead of spelling "degree".
This code always shows the alert no matter what is typed?
var alphanumers = /^[a-zA-Z0-9]+$/;
if(!alphanumers.test($("#notes").val())){
alert('You have special characters on instructions field.');
e.preventDefault();
return false;
}
This works for me:
HTML:
<h1>DEMO1</h1>
<input type="text" id="data" name="data" onkeyup="checkInput()">
<h1>DEMO2</h1>
<form action="#" method="post" onsubmit="return checkForm(this)">
<input type="text" id="data2" name="data" value="123abc+-*/">
<input type="submit">
</form>
Javascript:
DEMO1:
function checkInput(){
var testit = $('#data').val();
if( /[^a-zA-Z0-9\-\/]/.test( testit ) ) {
$('#data').css('background', '#f00');
}else{
$('#data').css('background', '#fff');
}
}
DEMO2:
function checkForm( theForm ){
var testit = $('#data2').val();
if( /[^a-zA-Z0-9\-\/]/.test( testit ) ) {
$('#data2').css('background', '#f00');
return false;
}else{
$('#data2').css('background', '#fff');
return true;
}
}
Demo: http://codesheet.org/codesheet/dMslCMmZ
I totally love this script! :
$("input").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(e.keyCode == 67 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(e.keyCode == 88 && 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 or alphabet and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 90)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
Here is the original source on stackoverflow, its for inputs to stop anything but nubers, i modified it a bit, hope it helps!
Try the jsfiddle

JQuery number only validation

$('.alphaOnly').bind('keypress', function(event){
var regex = new RegExp("^[ A-Za-z-.']*$");
validation(event, regex);
});
This is my validation for number only in a input. It works prefectly on desktop, iphone but not in android specifically samsung phone.
Does anyone of you ever encountered this kindof problem?
There are two way to achieve this.
1. Use onkeypress event of javascript and allow to enter numeric value only. In this way you will not able to enter decimal values.
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
Check below snippet. In this way you will be able to enter decimal values.
$(document).ready(function() {
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(e.keyCode == 67 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(e.keyCode == 88 && 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();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<input type="text" id="txtboxToFilter" />
Maybe you should try this way
var regex = new RegExp('\\d');
Have no Samsung, but on my android device works as it should
jsfiddle.

Validate and append phone input Jquery

I have some input field that always has to have + first in input
HTML
<input id="phone">
JS
$("#phone").keydown(function (e) {
$(this).get(0).value+="+";
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 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();
}
});
The problem is you can see in this fiddle
http://fiddle.jshell.net/nqkeuspf/
UPDATE
$("#phone").keydown(function (e) {
var firstChar = $(this).val().substr(0, 1);
// Check first character.
if (firstChar != '+'){
$(this).val('+' + $(this).val())
}
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190,107]) !== -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();
}
});
The problem is that it doesn not check +
Fiddle
http://fiddle.jshell.net/bjsrk83j/3/
Add this as keypress handler. It allows only numbers and you can supply it with a filter to allow other characters like +. Esc allows the user to cancel.
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
function handleInputKey(filter, e) // append filter as string '+-.,' for example.
{
if (!e) {
var e = window.event;
}
//allow only numeric input
//48-57 and 96-105 (keyboard left and numpad)
//also delete, back space, esc, enter, arrows and tab
if ((filter && filter.match(escapeRegExp(String.fromCharCode(e.which)))) || ((e.keyCode >= 48 && e.keyCode <= 57) && (!e.shiftKey && !e.altKey && !e.ctrlKey))) {
return true;
} else {
e.preventDefault();
return false;
}
}
//the onkeydown handler
function handleInputKeyFinish(e) {
if (!e) {
var e = window.event;
}
if (e.keyCode == 27) {
this.blur();
}
}
function stripAndAppendPlus(e) {
//when the users pastes a value delete invalid characters.
e.target.value = e.target.value.replace(/[^0-9]/g, "");
e.target.value = "+" + e.target.value;
}
$("#phone").keydown(handleInputKeyFinish);
$("#phone").keypress(handleInputKey.bind($("#phone")[0], null));
$("#phone").blur(stripAndAppendPlus);
Solution in Fiddle: http://fiddle.jshell.net/bqa87bwh/1/
Even simpler not using jQuery or JavaScript. This is HTML5 so not compatible with older browsers.
<input type="phone" pattern="^\+?\d{7,13}$" required />
pattern checks the input against a reg ex. This reg ex allows phone numbers consisting out of 7 to 13 numbers and they can begin with a +.
required --> this field has to contain a value otherwise the form won't be submitted.
Solution in Fiddle: http://fiddle.jshell.net/e76t41rj/1/

How to allow only numbers in a texbox but also allow entry with French keyboard

I have the following code to allow only numbers to be entered (other logic is removed for brevity).
$("input").keydown(function (event) {
var key = event.keyCode;
if ((key < 48 || key > 57) && (key < 96 || key > 105) || event.shiftKey) {
event.preventDefault();
}
});
This code works fine in English keyboards but on French keyboards the shift key is used so the logic fails there. If i remove the shift the logic fails in english keyboards.
Is there a way to detect a number is being pressed in the keydown event that will work on any type of keyboard?
Thanks
Use a custom function to check if the value of the keydown is numeric. From this previous answer (Validate decimal numbers in JavaScript - IsNumeric()):
function isNumber(n)
{
return !isNaN(parseFloat(n)) && isFinite(n);
}
And your handler UPDATED:
$("input").keydown(function (event) {
var code = event.keyCode;
//Allows left and right arrows, backspace, and delete
if(code == 37 || code == 39 || code == 8 || code == 46)
return;
var character = String.fromCharCode(code);
if(event.shiftKey || !isNumber(character)){
event.preventDefault();
}
});
I have found that event.key works better than event.keyCode. The event handler needs to be onkeydown for it to work properly. The check for whether it's a number needs to come first. Here's my code. Tested to work on IE11, Edge, Chrome, and Firefox.
$("input").keydown(function (event) {
var code = event.keyCode;
var key = event.key;
if (!isNaN(Number(key)))
return;
// allow backspace, delete, left & right arrows, home, end keys
if (code == 8 || code == 46 || code == 37 || code == 39 || code == 36 || code == 35) {
return;
} else {
evt.preventDefault();
}
});
#HostListener('keydown', ['$event']) onKeyDown(event) {
if ((e.keyCode < 48 || e.keyCode > 57) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
} else if (!this.isNumber(e.key)) {//For french keyboard
e.preventDefault();
}
}
}
isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
I had a similar problem because of 2 different keyboards. And I solve that by checking if is not a number in the key value instead of the keyCode value.
Would this work?
$("input").bind("propertychange input textInput", function() {
this.value = this.value.replace(/[^\d.]/g, "");
});
Of course, this trims the value after the input event, so I'm not sure if that's what you want

Categories