Input box onchange only allow numbers and one dot - javascript

I am creating an input box with an onChange function that will check to see if the characters are only digits and only allow up to one period/dot '.'
The function I have here is not working:
function addPercentSeparator(n) {
let str = n;
let match = str.match(/\d*\.\d*/)
if (match) {
return str;
}
}
I also tried: let match = str.match(/^([0-9]+(\.[0-9]+)?)/)
What I am trying to achieve is only allowing for one period.
If the user enters a number without a period, it will append a period to end of string when they click outside the input box.

This regex is supposed to do the trick:
^\d*\.?\d*$
But if you'll ask me, I would make sure there are digits before the dot, using ^\d+\.?\d*$.
Explanation:
As the dot isn't mandatory, I've added the ?, which symbolizes "0 or 1 occurrences".
I've also added the ^ and the $ to make sure no parts of the string will be matched if the whole string is illegal.
I hope this works for you!

Related

Regex for coercing input for phone number in javascript

I have an input for a phone number in french format
The input accepts two kinds of format, so i can input this:
0699999999
+33699999999
no check is done for the length of the number.
The table in database, the field is of varchar 12, i can have shorter input though.
The constraints: input contains only digits from 0 to 9, optional '+' sign accepted only if it starts the string, not after.
Currently i am in Angular with a directive, in that directive the heart is this expression :
var transformedInput = inputValue.replace(/[^0-9]/g, '');
i want the optional leading '+' sign, how can i achieve this?
thanks.
You could make the plus sign optional:
if (/\+?\d*/.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
subject is the text you want to check. \+ makes the plus sign a literal and the questionmark makes it optional.
If you just want to check wether ther is a plussign drop the questionmark. But if that is your goal don't use a regex. That is too much overhead. Simply get the first charactor of the trimmed string and check for the plus.
Change it to
var transformedInput = inputValue.replace(/[^0-9\+]/g, '').replace(/(.)\+/g, '$1');
Note - this will NOT add a + unless there is already a + in the input
What it does is
Do not remove the + symbol on the first replace
Remove every + symbol that is preceded by some character on the 2nd replace

Javascript to insert decimal to the ones place onkeyup has period persist after clearing the textbox

I have some simple javascript that automatically inserts a decimal in the numbers as you type. Three functions for one, two, and three decimal places. The two and three decimal place functions work how I desire, where when you backspace or clear the textbox, the placeholder text is replaced. However the one decimal place function leaves the period in the textbox after backspacing or deleting. What do I need to do to allow it to function like the other two?
The functions are as follows:
function formatAsDollars1(el) {
el.value = el.value.replace(/[^\d]/g, '').replace(/(\d?)$/, '.$1');
}
function formatAsDollars2(el) {
el.value = el.value.replace(/[^\d]/g, '').replace(/(\d\d?)$/, '.$1');
}
function formatAsDollars3(el) {
el.value = el.value.replace(/[^\d]/g, '').replace(/(\d\d\d?)$/, '.$1');
}
I set up a JSFiddle to show what I mean here
Here is why the last two functions work but the first one doesn't:
When inserting a ? modifier, it only affects the last "element" in your regex. For example, /\s\d?/ looks for a whitespace character followed by an optional digit, not an optional whitespace and digit.
So in the last two functions, it looks for one or two digits with an optional second or third digit to replace. However, in the 1 decimal function it looks for an optional digit, which is everything pretty much.
Therefore, removing the question mark should fix your error, i.e.
function formatAsDollars1(el) {
el.value = el.value.replace(/[^\d]/g, '').replace(/(\d)$/, '.$1');
}
Remove the question mark in your formatAsDollars1's replace regex:
function formatAsDollars1(el) {
el.value = el.value.replace(/[^\d]/g, '').replace(/(\d)$/, '.$1');
}

Need a RegExp to filter out all but one decimal point

I'm using the following code to negate the characters in the regexp. By checking the inverse, I can determine if the value entered is correctly formatted. Essentially, any digit can be allowed but only one decimal point (placed anywhere in the string.) The way I have it now, it catches all numerals, but allows for multiple decimal points (creating invalid floats.) How can I adjust this to catch more than one decimal points (since I only want to allow for one)?
var regex = new RegExp(/[^0-9\.]/g);
var containsNonNumeric = this.value.match(regex);
if(containsNonNumeric){
this.value = this.value.replace(regex,'');
return false;
}
Here is what I'm expecting to happen:
First, valid input would be any number of numerals with the possibility of only one decimal point. The current behavior: The user enters characters one by one, if they are valid characters they will show up. If the character is invalid (e.g. the letter A) the field will replace that character with ''(essentially behaving like a backspace immediately after filling the character in. What I need is the same behavior for the addition of one too many decimal points.
As I understand your question the code below might be what you are looking for:
var validatedStr=str.replace(/[^0-9.]|\.(?=.*\.)/g, "");
It replaces all characters other then numbers and dot (.), then it replaces all dots followed by any number of 0-9 characters followed by dot.
EDIT based on first comment - the solution above erases all dots but the last, the author wants to erase all but the first one:
Since JS does not support "look behind", the solution might be to reverse string before regex, then reverse it again or to use this regex:
var counter=0;
var validatedStr=str.replace(/[^0-9.]|\./g, function($0){
if( $0 == "." && !(counter++) ) // dot found and counter is not incremented
return "."; // that means we met first dot and we want to keep it
return ""; // if we find anything else, let's erase it
});
JFTR: counter++ only executes if the first part of condition is true, so it works even for strings beginning with letters
Building upon the original regex from #Jan Legner with a pair of string reversals to work around the look behind behavior. Succeeds at keeping the first decimal point.
Modified with an attempt to cover negatives as well. Can't handle negative signs that are out of place and special cases that should logically return zero.
let keep_first_decimal = function(s) {
return s.toString().split('').reverse().join('').replace(/[^-?0-9.]|\.(?=.*\.)/g, '').split('').reverse().join('') * 1;
};
//filters as expected
console.log(keep_first_decimal("123.45.67"));
console.log(keep_first_decimal(123));
console.log(keep_first_decimal(123.45));
console.log(keep_first_decimal("123"));
console.log(keep_first_decimal("123.45"));
console.log(keep_first_decimal("a1b2c3d.e4f5g"));
console.log(keep_first_decimal("0.123"));
console.log(keep_first_decimal(".123"));
console.log(keep_first_decimal("0.123.45"));
console.log(keep_first_decimal("123."));
console.log(keep_first_decimal("123.0"));
console.log(keep_first_decimal("-123"));
console.log(keep_first_decimal("-123.45.67"));
console.log(keep_first_decimal("a-b123.45.67"));
console.log(keep_first_decimal("-ab123"));
console.log(keep_first_decimal(""));
//NaN, should return zero?
console.log(keep_first_decimal("."));
console.log(keep_first_decimal("-"));
//NaN, can't handle minus sign after first character
console.log(keep_first_decimal("-123.-45.67"));
console.log(keep_first_decimal("123.-45.67"));
console.log(keep_first_decimal("--123"));
console.log(keep_first_decimal("-a-b123"));

jquery regex replace non numeric characters but allow plus

$('#target').val($('#target').val().replace(/[^\d]/g, ""));
I use the above code to leave only numeric characters in an input value I would also like to allow '+' and '-'.
How would I modify the regex to allow this?
Help much appreciated
Put - and + in the character class.
$('#target').val($('#target').val().replace(/[^-+\d]/g, ""));
FWIW I use a couple of input classes that I control with jQuery:
<input class="intgr">
<input class="nmbr">
$("input.intgr").keyup(function (e) { // Filter non-digits from input value.
if (/\D/g.test($(this).val())) $(this).val($(this).val().replace(/\D/g, ''));
});
$("input.nmbr").keyup(function (e) { // Filter non-numeric from input value.
var tVal=$(this).val();
if (tVal!="" && isNaN(tVal)){
tVal=(tVal.substr(0,1).replace(/[^0-9+\.\-]/, '')+tVal.substr(1).replace(/[^0-9\.]/, ''));
var raVal=tVal.split(".")
if(raVal.length>2)
tVal=raVal[0]+"."+raVal.slice(1).join("");
$(this).val(tVal);
}
});
intgr strips all non-numeric
nmbr accepts +, -, . and 0-9. The rest of the string gets stripped of all but 0-9 and the first . If you are OK with the + and - being anywhere, Bamar's solution is perfect, short and sweet. I needed the +/- to be only in the first character position if at all, and only one . (i.e. strip out beyond the first period so 2.5.9 would be 2.59)

Commas messing with number input in Javascript

I have a page with some elements that are controlled by the user. One of these is a text input field, where the user is supposed to input a number. Everything works well if the user only inputs digits (EG 9000), but is the user uses comma notation (the being 9,000) javascript doesn't take the input as an integer.
How can I remove the commas and/or force the input to an integer? I tried using parseint(), but it doesn't seem to work with commas.
Use a global regular expression to replace all commas with an empty string:
var str = "12,345,678";
str = str.replace(/,/g, "");
parseInt(str, 10);
or even better
var s="jdjsghd0182.99";
var str = parseFloat(s.replace(/[^0-9 | ^.]/g, ''));
Or even better, given the general unreliability of user input, use this to get rid of all non-numeric characters:
var s = "9,Ljk876";
var t = parseInt(s.replace(/[^0-9]/g, ''));
alert ("s:" + s + ", t:" + t);
maybe
parseint(ny9000withCommas.replace(/\,/g,""))
lets talk about the restriction :
you can/should allow the user to enter both 9000 & 9,000
you can check validy via REGEX.
in the server side - you should eleminate the commas and treat it as integer.

Categories