jquery regex replace non numeric characters but allow plus - javascript

$('#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)

Related

Html5 input type number not prevent plus, minus symbols

I am using input type number and It's preventing character but it's unable to prevent plus, minus symbol or character. But I require to prevent all symbol.
<input type="number">
I have worked on it and create my customise regex and it's working fine but I want to know why it's working like that for input type number and how we can fix that.
You can do this using jquery
$('input').keypress(function (e) {
var txt = String.fromCharCode(e.which);
if (!txt.match(/[0-9]/)) {
return false;
}
});
Because that's exactly how the spec says it should work. The number input can accept floating point numbers, including negative symbols and the e or E character:
A floating-point number consists of the following parts, in exactly
the following order:
Optionally, the first character may be a "-" character.
One or more characters in the range "0—9".
Optionally, the following parts, in exactly the following order:
a "." character
one or more characters in the range "0—9"
Optionally, the following parts, in exactly the following order:
a "e" character or "E" character
optionally, a "-" character or "+" character
One or more characters in the range "0—9".
You can do it with simple and a minimum limit for your number. Something like this:
<input min="0" type="number" step="1">
Now adding + or - signs make field value invalid and step=1 is for when you only need unsigned integers. If you don't need that, simply remove it.
Edit
If you don't want to + and - signs show in the filed, plus don't accept that input, you need to use some js.
Here is the simplest pure js solution I think:
Your html code:
<input min="0: type="number" step="1" onkeypress="removeSigns()" id="my-input">
And now you need to add this little script to your page:
function removeSigns() {
var input = document.getElementById('my-input');
input.value = parseInt(input.value.toString().replace('+', '').replace('-', ''))
This script gets the element that has my-element id, then overwrite its value.
The new value is int version of old value after replacing + and - signs in it with an empty string(removing them from the string in reality).
This solution is good when you only have one input, if you had more number input, you should change the removeStrin to a version that gives input object from this in the onkeypress. But I don't add that version because of simplicity of the solution.
}

Prevent repeated '+' character simultaneously on Key Up

I had regular expression which is onkeyup="this.value=this.value.replace(/[^aA0-9 +]/g,'');
Which is allow string only number with '+' symbol i.e 1+2+3
I had functionality of + for combine.
But in some time it allow example '+1' and also '1++3+' or '+++4+5'.
How to prevent repeated '+' and on start with '+' on keyup event so that my functionality will work.
Any suggestion.
Thank You.
Attach the event listener properly using Javascript, and then you can replace multiple pluses in a row with a single plus by matching \++ (literal plus, repeated) and replacing with +. Also note that 0-9 in a character set reduces to \d, which is a bit nicer to read:
element.addEventListener('keyup', function() {
this.value = this.value
.replace(/[^aA\d +]/g,'')
.replace(/\++/g, '+');
});
You might also want to check for spaces around pluses so as to avoid, for example, a+ +a. If that's the case, then you can use:
.replace(/ *\+[ +]/g, ' + ')
That will replace optional spaces, followed by a plus, followed by any combination of pluses and spaces, with a single plus surrounded by a space on each side. (of course, you could also replace with a plus alone, without spaces, if you wanted)
var element=document.getElementById("txtSum");
element.addEventListener('keyup', function() {
this.value = this.value
.replace(/\s/g, '') // Removes space
.replace(/^\++/g, '') // Remove begining with +
.replace(/[^aA\d +]/g,'')
.replace(/\++/g, '+'); // Replace multiple +
});
<input type="text" id="txtSum"/>

Input box onchange only allow numbers and one dot

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!

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

Replacing alpha characters and spaces in string with jQuery

I have a string that allows only numbers
$(this).val($(this).val().replace(/([a-zA-Z])/g, ""));
How can I add a space, so this will get replaced with "" same way in one string?
To match only non-numerics, you would do [^0-9] instead of [a-zA-Z] (this is called a negated character class).
If you want an input to allow only numbers, with HTML5 you can simply do <input type="number">. For wider support, there are plenty of JavaScript solutions, have a look at How to allow only numeric (0-9) in HTML inputbox using jQuery? as suggested in the comments.
Just add the space to your Regex:
"asfasd asdf asdf".replace(/([a-zA-Z ])/g, "");
Yields:
""
Edit:
I misunderstood your question. If you want to prevent every input but numbers use this regex:
function removeNotAllowedChars($input) {
$input.val($input.val().replace(/[^0-9]/g, ''));
}
$('#myText')
.keyup(function() {
var $input = $(this);
removeNotAllowedChars($input);
})
.change(function() {
var $input = $(this);
removeNotAllowedChars($input);
});
Using these script removes the input instantly if the user types the character and if he pastes the input after the focus changes. Try it here: JSFiddle
use \s - Matches a single white space character, including space, tab, form feed, line feed. Equivalent to
Regex Guide

Categories