Javascript Validation not working on Mobile - javascript

I have used some javascript for validation eg. allow only numbers or text, restrict length.it's working fine on desktop but on mobile below mention javascript is not working.
/// allow numbers only
$('#pincode, #billing_phone').keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
return false;
}
});
//allow characters only
$(function() {
$("#billing_first_name, #billing_last_name").keydown(function(e) {
if ( e.which != 9) {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
});
// restrict length
$("#reg_billing_city").attr('maxlength',30);
$("#billing_phone, #reg_billing_phone, .qty").attr('maxlength',10);
What I have Tried:
I have written my javascript according to screen width like this
if (screen.width < 600) {// javascript goes here }
and it's working fine on desktop but on mobile, it's not working.
Can you please help to identify the problem?

Related

Jquery Max Value Validation for Number Field

I am working on responsive Html Design. There are some number fields and they have some requirements.
Control take only number
After decimal it take only two digits
Max value not greater than 9999999999
Max Length is 9 in case float value it will (999999.99)
All validation work on key press or key up
I implement this code it working fine for desktop and other mobile device but not working on any Samsung tab. If i use input type="number" then maxlength or max value not working in Samsung tab. Plz help me.
CODE
$("#txtnumber").keydown(function (event) {
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 || event.keyCode == 110) {
} else {
event.preventDefault();
}
if (($(this).val().indexOf('.') !== -1 && event.keyCode == 190) || $(this).val().indexOf('.') !== -1 && event.keyCode == 110)//Allow only one time decimal to input
event.preventDefault();
});
$("#txtnumber").keyup(function () {
var number = ($(this).val().split('.'));
if (number[1].length > 2) {
var FNumber = parseFloat($("#txtnumber").val());
$("#txtnumber").val(FNumber.toFixed(2));
}
});
JSFiddle URL
Here is an example using jquery,
$("#txtnumber").on('keyup keydown', function () {
if (isNaN(($(this).val()))) {
$(this).val($(this).val().substring(0, ($(this).val().length - 1)));
}
if ($(this).val().length > 10 && $(this).val().indexOf('.') == -1) {
$(this).val($(this).val().substring(0, 10));
}
if ($(this).val().indexOf('.') !== -1 && $(this).val().length > 9) {
$(this).val($(this).val().substring(0, 9));
}
if (($(this).val().indexOf('.') !== -1)) {
var decimal = $(this).val().split('.');
if (decimal[1].length > 2) {
$(this).val($(this).val().substring(0, ($(this).val().length - 1)));
}
}
});
Updated Fiddle

allow tab and other keys in input textbox

Below is my javascript code which restrict the user for following:
1) only allow numeric and upto two decimal points.
It also restrict the user for tab, backspace , delete, left and right arrow keys.
I tried by adding condition event.which != 8/9/37/38 but not succeed.
Below is the code:
$('#txtprice').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();
}
});
can any one please correct me here.
EDITED: Modified as below but not work.
$('#txtprice').keypress(function (event) {
if (event.which == 8 || event.which == 9 || event.which == 37 || event.which == 38) {
event.preventDefault();
return;
}
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();
}
});
Thanks
You simply just have to allow what you want, not determine what you don't want. This is easy by determining if the keyCode is a period (190) or in between 48 and 57.
function validateNum(e) {
var elem = document.getElementById("txtprice");
if (e.keyCode >= 48 && e.keyCode <= 57 || e.keyCode == 190) {
var txt = elem.value;
if (e.keyCode == 190 && txt.match(new RegExp('\\.','g')).length > 1) {
e.preventDefault();
}
} else {
e.preventDefault();
}
}
Here is a working js fiddle: http://jsfiddle.net/e72uqvbv/
UPDATE: I miss understood the period situation request, I have updated my answer.

Validate Number in Javascript not working in Firefox

This validation return true when the input text is 0 to 10 (0,1,2,3,4,5,6,7,8,9,10).
The backspace do not work in Firefox ,in Google Chrome ,Internet Explorer work well.I tried to enable the charcode of the backspace but the problem persist.
How can I make it works in firefox ?
I have this:
<script>
function compruebacampo(evt, campotexto)
{
var charCodeOfZero = 48;
var numberJustEntered = evt.charCode - charCodeOfZero;
var fullString = campotexto.value + "" + numberJustEntered;
var matchesOne = false;
for (var i = 0; i <= 10; i++) {
if (fullString == ("" + i))
matchesOne = true;
}
if (!matchesOne)
return false;
}
</script>
<input type="textbox" onkeypress="return compruebacampo(event,this)" >
Any help would be very appreciated.
I was going to write a function that used browser-specific cases (via navigator.userAgent), but I figured that was too clunky and complicated. I think the easiest thing to do is to bind an event handler to that specific input and have it listen to the keyCodes (keys in FireFox). This method also avoids inline JavaScript, which is definitely a plus.
event.keyCode < 58 && event.keyCode > 47
For non-FireFox browsers, this captures all the digits (0-9).
event.key > -1 && event.key < 10
In FireFox, this will capture all the digits (0-9), since the above will fail.
event.keyCode == 8 || event.keyCode == 0
Captures backspaces and allows them to go through.
HTML
<input type="text" id="numberInput">
JavaScript
document.getElementById("numberInput").onkeypress = function (event) {
if (event.keyCode < 58 && event.keyCode > 47 || event.key > -1 && event.key < 10) {
/* nothing */
} else if (event.keyCode == 8 || event.keyCode == 0) {
/* nothing */
} else {
event.preventDefault();
}
}
I tested in Safari, FireFox, and Chrome. It worked in all three for me. I'm sure you could rewrite those booleans to just one if block.
fiddle
Try this alternative which will allow only numbers to be input on the field: http://jsfiddle.net/6faHh/
function compruebacampo(e, campotexto) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
}
$('input').keypress(function (e) {
if ($(this).attr('id') == "txtBoxId") {
regex = new RegExp("^[0-9\b]+$");
var charString = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(charString)) {
return true;
}
else {
e.preventDefault();
return false;
}
}
}

JQuery allow only two numbers after decimal point

I found the following JQuery function here which prevents a user from entering anything that's not a number or a single decimal. The function works well but I'd like to improve it to prevent the user from entering 3 or more decimal places i.e. disallow 99.999 and allow 99.99. Any ideas?
function checkForInvalidCharacters(event, inputBox){
if ((event.which != 46 || inputBox.val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
};
The logic is every time a user entering a number you have to check two things.
Has the user entered decimal point?
Are the decimal places more than two?
For the first one you can use $(this).val().indexOf('.') != -1For the second one you can use $(this).val().substring($(this).val().indexOf('.'), $(this).val().indexOf('.').length).length > 2
EDIT-1
Also, you have to add event.which != 0 && event.which != 8 so that arrow keys and backspace work in Firefox (Manoj comment)
EDIT-2
Also, you have to add $(this)[0].selectionStart >= text.length - 2 so that you can add digits if the cursor is to the left of the decimal point (BIdesi comment)
EDIT-3
Also, you have to check if user deleted . and placed it somewhere else creating a value with more than 2 digits after the decimal. So you have to add
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3)); for cutting extra digits (Gilberto Sánchez comment)
EDIT-4
To handle pasted data, you must bind a paste event handler.Then you have to check if pasted data have . withtext.indexOf('.') > -1 and more than 2 digits after the decimal with text.substring(text.indexOf('.')).length > 3. If so, you have to cut extra digits. Also you have to check that user entered numeric input with $.isNumeric() (darasd comment).
Here is the code:
$('.number').keypress(function(event) {
var $this = $(this);
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((event.which == 46) && (text.indexOf('.') == -1)) {
setTimeout(function() {
if ($this.val().substring($this.val().indexOf('.')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
}
}, 1);
}
if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 2) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
});
$('.number').bind("paste", function(e) {
var text = e.originalEvent.clipboardData.getData('Text');
if ($.isNumeric(text)) {
if ((text.substring(text.indexOf('.')).length > 3) && (text.indexOf('.') > -1)) {
e.preventDefault();
$(this).val(text.substring(0, text.indexOf('.') + 3));
}
}
else {
e.preventDefault();
}
});
.number {
padding: 5px 10px;
font-size: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="number" />
It can also be done with a regular expression:
$('.class').on('input', function () {
this.value = this.value.match(/^\d+\.?\d{0,2}/);
});
Name the css selector .class to whatever you like and put it on the input.
I've updated the function for a few extra cases.
It will allow negative numbers
It will allow you to edit the left of the decimal when there are already 2 digits to the right
It allows you to use the arrow keys and backspace when you are in Firefox
It also handles pasted data
/**
* Given an input field, this function will only allow numbers with up to two decimal places to be input.
* #param {object} element
* #return {number}
*/
function forceNumber(element) {
element
.data("oldValue", '')
.bind("paste", function(e) {
var validNumber = /^[-]?\d+(\.\d{1,2})?$/;
element.data('oldValue', element.val())
setTimeout(function() {
if (!validNumber.test(element.val()))
element.val(element.data('oldValue'));
}, 0);
});
element
.keypress(function(event) {
var text = $(this).val();
if ((event.which != 46 || text.indexOf('.') != -1) && //if the keypress is not a . or there is already a decimal point
((event.which < 48 || event.which > 57) && //and you try to enter something that isn't a number
(event.which != 45 || (element[0].selectionStart != 0 || text.indexOf('-') != -1)) && //and the keypress is not a -, or the cursor is not at the beginning, or there is already a -
(event.which != 0 && event.which != 8))) { //and the keypress is not a backspace or arrow key (in FF)
event.preventDefault(); //cancel the keypress
}
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 2) && //if there is a decimal point, and there are more than two digits after the decimal point
((element[0].selectionStart - element[0].selectionEnd) == 0) && //and no part of the input is selected
(element[0].selectionStart >= element.val().length - 2) && //and the cursor is to the right of the decimal point
(event.which != 45 || (element[0].selectionStart != 0 || text.indexOf('-') != -1)) && //and the keypress is not a -, or the cursor is not at the beginning, or there is already a -
(event.which != 0 && event.which != 8)) { //and the keypress is not a backspace or arrow key (in FF)
event.preventDefault(); //cancel the keypress
}
});
}
forceNumber($("#myInput"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myInput" />
thank you! I have added the possibility of deleting the numbers and '.' once typed:
The event.keyCode !== 8 does that action for backspace.
The event.keyCode !== 46 does that action for delete.
$( document ).ready(function() {
$('#Ds_Merchant_Amount').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) ) {
if (event.keyCode !== 8 && event.keyCode !== 46 ){ //exception
event.preventDefault();
}
}
if(($(this).val().indexOf('.') != -1) && ($(this).val().substring($(this).val().indexOf('.'),$(this).val().indexOf('.').length).length>2 )){
if (event.keyCode !== 8 && event.keyCode !== 46 ){ //exception
event.preventDefault();
}
}
});
});
Numeric values With Decimal Point up to 2 decimal point validation.
Dependency jQuery.
HTML -
<span>Float</span>
<input type="text" name="numeric" class='allownumericwithdecimal'>
<div>Numeric values only allowed (With Decimal Point) </div>
JQuery Code -
Method 1-
$(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
var patt = new RegExp(/[0-9]*[.]{1}[0-9]{2}/i);
var matchedString = $(this).val().match(patt);
if (matchedString) {
$(this).val(matchedString);
}
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
Method 2 -
$(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
var patt = new RegExp(/(?<=\.\d\d).+/i);
$(this).val($(this).val().replace(patt, ''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
I have updated this routine to allow standard editing features as these were prevented in the above code. (This routine is just for processing a float but can be adapted to allow only 2 digits after the decimal)
var value = $(this).val().toString();
// Allowed Keys
if (event.which === 8 || event.which === 46 // Character delete
|| event.which === 16 || event.which === 17 // Modifier Key
|| event.which === 37 || event.which === 39 // Arrow Keys
|| (event.key.toLowerCase() === "a" && event.ctrlKey) // Select All
|| (event.key.toLowerCase() === "c" && event.ctrlKey) // Copy
|| (event.key.toLowerCase() === "x" && event.ctrlKey) // Cut
|| (event.key.toLowerCase() === "v" && event.ctrlKey) // Paste
|| (event.which === 45 && event.ctrlKey) // Old school copy (CTRL + INSERT)
|| (event.which === 46 && event.shiftKey) // Old school cut (SHIFT + DELETE)
|| (event.which === 45 && event.shiftKey) // Old school paste (SHIFT + INSERT)
|| (event.which === 35) // END
|| (event.which === 36) // HOME
|| (event.which === 35 && event.shiftKey) // SHIFT + END
|| (event.which === 36 && event.shiftKey) // SHIFT + HOME
)
{
return;
}
else if (event.which === 190) // Process decimal point
{
if (value == "" || value.indexOf(".") > -1)
{
event.preventDefault();
}
}
else if (event.which < 48 || event.which > 57 || event.ctrlKey || event.shiftKey) // Reject anything else that isn't a number
{
event.preventDefault();
}
Try this
HTML
<input type="text" id="min_rent" name="min_rent" onkeypress="return isPrice(event,$('#min_rent').val())">
Jquery
function isPrice(evt,value) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if((value.indexOf('.')!=-1) && (charCode != 45 && (charCode < 48 || charCode > 57)))
return false;
else if(charCode != 45 && (charCode != 46 || $(this).val().indexOf('.') != -1) && (charCode < 48 || charCode > 57))
return false;
return true;
}
Worked Link
demo

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