Regular Expression on keypress for decimals with negative values - javascript

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);
}

Related

How to executing a validation in text box number format like 44.44

I want to Check the value to both javascript and php ,which one should be like this format 22.22 or 00.44 or 44 or 55.00.
I have the below code.
$(function(){
// $('.pixcel_rate').keypress(function (event) {
// return isNumber(event, this)
// });
$('.pixcel_rate').keypress(function (event) {
return validateFloatKeyPress($(this).val());
});
});
// THE SCRIPT THAT CHECKS IF THE KEY PRESSED IS A NUMERIC OR DECIMAL VALUE.
function validateFloatKeyPress(evt,el) {
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(".");
console.log(caratPos);
console.log(dotPos);
if( caratPos >1 && dotPos>-1 && (number[0].length > 1)){
return false;
}
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
}
You can use preg_match in php to see if it matches the pattern.
preg_match("/^\d{2}\.\d{2}$|^\d{2}$/", $val);
This matches either two digits, dot, two digits. Or just two digits.
Example test cases:
https://3v4l.org/G6D8l
You can use regex to achieve this. Below is the regex for your requirement.
https://regex101.com/r/N5gbqs/3/
function validateFloatKeyPress(value) {
//returns null if it doesnt match the given regular expression
return value.toString().match(/^(\d{2}|\d{2}\.\d{2})$/)
}
function validateFloatKeyPress(value) {
//returns false if it doesnt match the given regular expression
return (/^(\d{2}|\d{2}\.\d{2})$/).test(value.toString())
}

what are key values for special characters?

function alphaOnly(event) {
var key = event.keyCode;
return ((key >= 8 && key <= 47) || (key >= 65 && key <= 222));
};
My function is not able to print # # $ % & ! * ( )
I could not find key codes for the above symbols. Please help me to accept these characters.
You can use regular expression instead on checking ascii values :
<script type="text/javascript">
function alphaOnly() {
var isValid = false;
var regex = /^[a-zA-Z%*#]*$/;
isValid = regex.test($("#field").val());
return isValid;
}
</script>

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

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 ..
}

replace number and symbol with jquery/javascript

Does anyone know how can I replace the number and symbol (excluding dash and single quote)?
Example:
if I have a string "ABDHN'S-J34H##$";
How can I replace the number and symbol to empty and return me value "ABDHN'S-JH" ?
I have the following code to replay all the char and symbol to empty and only return me number
$(".test").keyup(function (e) {
orgValue = $(".test").val();
if (e.which != 37 && e.which != 39 && e.which != 8 && e.which != 46) {
newValue = orgValue.replace(/[^\d.]/g, "");
$(".test").val(newValue);
}
});
You should allow only letters, dash and single quotes, like this:
newValue = orgValue.replace(/[^a-zA-Z'-]/g, "");
Anything else will be replaced by "".
You can use this regex:
string.replace(/^[a-zA-Z'-]+$/, '')
The caret ^ inside a character class [] will negate the match. This regex will convert all characters other than a-z, A-Z, single quote and hyphen to empty
You could replace symbols by skipping them through keycode value on the keyboard.
Link for keycode values for reglar keyboard:
http://www.w3.org/2002/09/tests/keys.html
$("#your control").bind("keydown keyup", doItPlease);
function doItPlease(e)
{
// First 2 Ifs are for numbers for num pad and alpha pad numbers
if (e.which < 106 && e.which > 95)
{
return false; // replace your values or return false
}
else if (e.which < 58 && e.which > 47)
{
// replace your values or return false
} else {
var mycharacters = [8, 9, 33, 34, 35 // get your coders from above link];
for (var i = 0; i < mycharacters.length; i++) {
if (e.which == mycharacters[i]) {
// replace your characters or just
// return false; will cancel the key down and wont even allow it
}
e.preventDefault();
}
"ABDHN'S-J34H##$".replace(/[^\-'\w]/g, '')
"ABDHN'S-J34H##$".replace(/[0-9]|[\'##$]/g, "");

Javascript limit text input characters

I am wanting to restrict the input characters for a text box to [a-z0-9_-]. However whenever if do this buttons like backspace and the arrow keys don't work. I have found some attempts on this website and others but either they don't work properly on all browsers or they use a black list. For example the W3Schools website example black lists numbers. Is there a way to use white list (the one above) and still allow keys like backspace, arrows, home, end etc? Or do I have to add everyone of the key codes that match the keys I want to allow? I do something like this (this is shortened for simplicity).
EDIT - Added code
<input type="text" onkeypress="return checkInput();">
function checkInput(){
return /[a-z0-9_-]/gi.test(String.fromCharCode(window.event.keyCode));
}
Just change the regex in the example to something like this:
numcheck = /[^a-z0-9_-]/;
Or better yet, avoid the double negative with:
numcheck = /[a-z0-9_-]/;
return numcheck.test(keychar);
Then you can look up the keycodes of backspace, etc. and check for them too:
if (keychar === 8) return true;
...
Or even put them in your regex:
numcheck = /[a-z0-9_\x08-]/;
You haven't provided any code samples, so it's hard to be specific in a response, but as a general strategy, try this: instead of trying to whitelist characters that can be input while they are being typed in, validate the contents of the text box after every key stroke to make sure that it still contains valid characters. If it doesn't, remove the last character entered.
This approach will allow special keys like backspace, etc., while at the same time achieve what it sounds like you are really after: a valid value in the text box.
Yes you can limit the input of characters. For example create a function that checks what is going on, return true if everything is OK and false if not:
// return true for 1234567890A-Za-z - _
function InputCheck(e) {
if ((e.shiftKey && e.keyCode == 45) || e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
if (e.which == 45 || e.which == 95 || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122))
return true;
return false;
}
return true;
}
once you have the function, hook it into you input (this is with jQuery):
$('#InputID').keypress(InputCheck);
You can make as complicated a check as you want, for example this will allow for USD money values:
function InputCheck(e) {
if ((e.shiftKey && e.keyCode == 45) || e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && e.which != 46 && e.which != 36) {
return false;
}
// . = 46
// $ = 36
var text = $(this).val();
// Dollar sign first char only
if (e.which == 36 && text.length != 0) {
return false;
}
// Only one decimal point
if (e.which == 46 && text.indexOf('.') != -1) {
return false;
}
// Only 2 numbers after decimal
if (text.indexOf('.') != -1 && (text.length - text.indexOf('.')) > 2) {
return false;
}
return true;
}
You can press any key you like, as long as you keep the value from including anything
not in the white-list.
inputelement.onkeyup=function(e){
e=e || window.event;
var who=e.target || e.srcElement;
who.value= who.value.replace(/[^\w-]+/g,'');
}
Add this code to onkeypress event.
var code;
document.all ? code = e.keyCode : code = e.which;
return ((code > 64 && code < 91) || (code > 96 && code < 123) || code == 8 || code == 32 || (code >= 48 && code <= 57));
For browser compatibility, You can add
var k = e.keyCode == 0 ? e.charCode : e.keyCode;

Categories