Why am I unable to enter % sign after my custom validation - javascript

I have a requirement wherein I can enter number not more than 100 (100 allowed). Additionally these number can have +, - sign at start and % at the end.
I have come up with the following function to validate. However, even after struggling a lot, I am unable to fix why I am not able to enter a % sign when I have already enter 2 digits.
Ex: after typing 10, I cant type % (Shift + 5)
My Function:
$scope.checkInputValidation = function(event, value) {
var key = event.keyCode;
var currentcharacter = String.fromCharCode(key);
if (key === 91 || key === 187 || key === 189 || (15 < key && key < 19) || (35 <= key && key <= 40)) {
return;
}
if (isNaN(currentcharacter) && ((currentcharacter !== "%") || (currentcharacter !== "+") || (currentcharacter !== "-") || (currentcharacter !== ""))) {
if ((key !== 46) && (key !== 8)) {
event.preventDefault();
return false;
}
}
var formattedValue;
if (value.indexOf('%') !== -1) {
formattedValue = value.replace('%', "");
} else {
formattedValue = value;
}
if (!isNaN(currentcharacter)) {
if (parseInt(formattedValue + currentcharacter) > 100 || parseInt(formattedValue + currentcharacter) < -100) {
event.preventDefault();
return false;
}
}
}
I would like to know the cause and how should I be able to enter %.

currentcharacter is never going to contain the % character. You have to check the keyCode for 5 (53) in combination with the event.shiftKey property.
if(key === 53 && event.shiftKey) {
.. % pressed ..
}

Related

Limiting an integer to an arrays indeces when incrementing/decrementing

Consider the following code (keyCode is used for backward compatibility):
/**
* Navigate through the items.
*
* #param {Event} event
* #return void
*/
navigate(event) {
if (event.keyCode === 38 || event.key === "ArrowUp") {
this.active = this.active + 1 > this.items.length ? 0 : this.active + 1;
}
if (event.keyCode === 40 || event.key === "ArrowDown") {
this.active = this.active - 1 < 0 ? this.items.length : this.active - 1;
}
}
If the above is not clear, what I am trying to do is the following:
When incrementing this.active, make sure it is not greater than the length of this.items, and if it is, return it to 0
When decrementing this.active, make sure it is not less than 0, and if it is, return it to the length of this.items
The above code works absolutely fine but I know that it can be done better and more efficiently. For instance, calling this.active -1 twice in inefficent.
Is there a way to gracefully achieve this using something along the lines of Math.min and Math.Max?
I'd use the modulo operator instead:
navigate(event) {
const { length } = items;
if (event.keyCode === 38 || event.key === "ArrowUp") {
this.active = (this.active + 1) % length;
} else if (event.keyCode === 40 || event.key === "ArrowDown") {
this.active = (this.active - 1 + length) % length;
}
}

Validate Credit card without regExp

I am trying to validate credit card number which may contain four tests of alphanumeric characters, separated by hyphens (-) or without hyphens. Not using regExp.
I have tried different ways but I can't figure out how to do it properly.
That's what I have done so far:
function isCredit(input) {
var i, code;
//if input.length > 19, stop execution
if(input.length > 19) return false;
for(i = 0; i < input.length; i++) {
code = input.charCodeAt(i);
//Matches to only numbers and Capital letters
if((code > 47 && code < 58) && (code > 64 && code < 91)) {
//if every 5th character is "-"
if((input.slice(4, 5) === "-") && (input.slice(9, 10) === "-") &&(input.slice(14, 15) === "-")) {
return true;
}
}
return false;
}
}
isCredit("12A4-56H8-43K6-36U3"); // returns true;
isCredit("4427A693CF324D14"); // returns true;
isCredit("----------------"); // returns false;
Any help and guidance appreciated!
I'm not exactly clear on your requirements. Here I'm assuming "12A556H8-43K636U3" is a valid card number if you allow hyphen omissions.
function isAlphaNum(ch) {
var code = ch.charCodeAt(0);
return ((code > 47 && code < 58) || (code > 64 && code < 91));
}
function isCard(str) {
var char, i = 0, x = [1,1,1,1,0,1,1,1,1,0,1,1,1,1,0,1,1,1,1];
while (char = str[i++]) {
if (x[0] == undefined) {
return false;
}
if (isAlphaNum(char)) {
if (x[0]) {
x.shift();
} else {
x.splice(0,2);
}
} else if (char == '-') {
if (!x[0]) {
x.shift();
} else {
return false;
}
} else {
return false;
}
}
return x[0] == undefined;
}

Regular Expression on keypress for decimals with negative values

Hi can someone help me to improve this regular expression on this function to include negative values?
the function is:
function Validate7EntY2Dec(e, field) {
key = e.keyCode ? e.keyCode : e.which
// backspace
if (key == 8) return true
// 0-9 a partir del .decimal
if (field.value != "") {
if ((field.value.indexOf(".")) > 0) {
if (key > 47 && key < 58) {
if (field.value == "") return true
regexp = /[0-9]{2}$/
return !(regexp.test(field.value))
}
}
}
// 0-9
if (key > 47 && key < 58) {
if (field.value == "") return true
regexp = /[0-9]{7}/
return !(regexp.test(field.value))
}
// .
if (key == 46) {
if (field.value == "") return false
regexp = /^[0-9]+$/
return regexp.test(field.value)
}
// other key
return false
}
as far as I get /[0-9]{2}$/ validates two digits after the decimal point, and /[0-9]{7}/ validates seven digist in the integer. I would like to this accept also negative values so the user can insert -1234567.12 for example.
I found this regex ^[+-]?[0-9]{1,9}(?:\.[0-9]{1,2})?$ on other question but dont know how to insert in my function.
Also found that adding a - on /[0-9]{7}/ will accept negative values but it didnt, i did this: /[-0-9]{7}/
I need to keep my function because its been used already.
thank you in advance!
edit:
After the recommendation of #Ian my code was like this:
function Validate7EntY2Dec_Neg(e, field) {
key = e.keyCode ? e.keyCode : e.which
// backspace
if (key == 8) return true
// 0-9 a partir del .decimal
if (field.value != "") {
if ((field.value.indexOf(".")) > 0) {
if (key > 47 && key < 58) {
if (field.value == "") return true
regexp = /[0-9]{2}$/
return !(regexp.test(field.value))
}
}
}
// 0-9
if (key > 47 && key < 58) {
if (field.value == "") return true
regexp = /[0-9]{7}/
return !(regexp.test(field.value))
}
// .
if (key == 46) {
if (field.value == "") return false
regexp = /^[+-]?[0-9]{7}\.[0-9]{2}$/
return regexp.test(field.value)
}
// other key
return false
}
The change is on "function if (key == 46)..."
if (key == 46) {
if (field.value == "") return false
regexp = /^[+-]?[0-9]{7}\.[0-9]{2}$/
return regexp.test(field.value)
}
#Ian how to escape - ??
^[+-]?[0-9]{7}\.[0-9]{2}$ should work. The caret forces start of string and the dollar the end. I have also forced a 7.2 digit number, I assume that is what you want. Also there is the optional +/- to start with.
I propose you stop worrying about keypresses and validate the whole field each time it's changed. I believe this wouldn't cause any performance problem and would vastly improve your code's maintainability.
I would then propose the following code :
function Validate7EntY2Dec_Neg(e, field) {
return /^[+-]?[0-9]{7}\.[0-9]{2}$/.test(field.value);
}

javascript validation allow only character and comma with backspace, arrow and delete keys

I need that textbox only allow characters and comma with arrow keys, backspace and delete keys
$(document).ready(function() {
$('#text').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z,]");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<input type="text" id="text" />
</body>
Check this fiddle
$(document).ready(function() {
$('#text1').keypress(function (e) {
var k = e.which;
var ok = k == 127 || k == 8 || k == 9 || k == 13 || k == 37 || k == 38 || k == 39 || k == 40;
ok = ok ||
k >= 65 && k <= 90 || // A-Z
k >= 97 && k <= 122 || // a-z
k == 44 ; // ,
if (!ok){
e.preventDefault();
}
});
});

Jquery keypress 37 issue, '%' and [ left arrow ] not work in IE 10

Good morning,
I facing a issue on the IE 10 where my keypress still can enter '%' but the FF and Chrome no such issue.
I found out that the key 37 is the [ left arrow ] which match with '%' in ASCII.
My sample code as below:
$('#refId').bind("keypress", function(event) {
// allow letters, numbers and keypad numbers ONLY
var key = event.charCode;
if((key >= 48 && key <= 57) ||
(key >= 65 && key <= 90) ||
(key >= 97 && key <= 122)){
return true;
}
//allow backspace, tab, left arrows, right arrow, delete
key = event.keyCode;
if(key == 8 ||
key == 9 ||
key == 37 ||
key == 39 ||
key == 46){
return true;
}
return false;
});
Can give me some idea how to fix this?
Thanks.
-fsloke
Use var key = event.which; instead and join the if-statements.
The event.which property normalizes event.keyCode and event.charCode.
It is recommended to watch event.which for keyboard key input.
- https://api.jquery.com/event.which/
$('#refId').on("keydown", function(event) {
// allow letters, numbers and keypad numbers ONLY
var key = event.which;
if((key >= 48 && key <= 57) ||
(key >= 65 && key <= 90) ||
(key >= 97 && key <= 122) ||
key == 8 ||
key == 9 ||
key == 37 ||
key == 39 ||
key == 46) {
return true;
}
return false;
});

Categories