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"/>
Related
I have an input field in which I want to allow only number and 1 comma. How could I make it accept only single comma?
$("#my-field").on("keyup", checkKey);
function checkKey() {
this.value = this.value.replace(/[^0-9,]/g, "");
}
You could do it like this:
function checkKey() {
var clean = this.value.replace(/[^0-9,]/g, "")
.replace(/(,.*?),(.*,)?/, "$1");
// don't move cursor to end if no change
if (clean !== this.value) this.value = clean;
}
// demo
document.querySelector('input').oninput = checkKey;
<input>
This will remove all repeated commas, and everything between them. That is not an issue, since you press one key at a time.
Remarks
This blocking way of input validation is user unfriendly. It is better to colour things, or put messages, than to make the keyboard disfunctional.
Consider using the <input type="number"> element, which has number validation built in.
The input event is often more useful for checking for changes in the input than keyup, since changes can also be made via mouse actions and the context menu.
If you want to allow dot instead of comma, then change every , with \. in the regular expressions, as . has a special meaning in regular expressions, and must be escaped to be taken as a literal character.
I'm trying to write a regular expression to validate some user entered text. I'd like to use the regular expression with an ngPattern directive so should avoid using the g flag.
Essentially, there are a number of "simple" rules.
There must be one or more words.
Single quotes (') are not allowed.
Double quotes (") are allowed but must be paired, i.e. open and closing.
Paired double quotes must wrap one or more words.
No white space is allowed between a double quote and the word it adjacently wraps.
An asterisk (*) is not allowed unless it immediately precedes a closing double quote and follows a word, without whitespace.
Here are some examples.
example match
'' false
' ' false
' foo' true
'foo' true
'foo bar' true
'foo bar*' false
'"foo' false
'"foo"' true
'" foo"' false
'"foo "' false
'"foo bar"' true
'"foo *"' false
'"foo*"' true
'foo*"' false
'"foo*" "bar*"' true
'foo "bar*"' true
'"foo* bar"' false
'"foo*" bar' true
I've created unit tests here
I'm struggling to get anywhere close,
I've got an expression like this
/(")(?:(?=(\\?))\2.)*?\1/
that will match text between paired double quotes. Something like this,
/^.*\*"$/
will match text that ends with '*"',
as you can see, I've got a long way to go, please help.
Is it possible that a regular expression is the wrong way to do this?
^(?=.*\b)(?=[^"]*("[^"]*"[^"]*)*$)(?![^"]*("[^"]*"[^"]*)*" *")(?!.*\*[^"])(?!.*[ "]\*)(?![^"]*("[^"]*"[^"]*)*[^"]*\*")(?![^"]*("[^"]*"[^"]*)*" \w)(?![^"]*("[^"]*"[^"]*)*"[^"]*\w ")'[^']*'$
See it in action
Good luck using this in your production codebase
Ok, so dafuq...
An important idea that we are going to reuse is how to reach a position, before which you know there were an even number of "s. Namely:
[^"]*("[^"]*"[^"]*)*
Unfortunately, we can't reuse patterns in javascript regexes, so we will have to repeat it where ever we need it. Namely:
Double quotes (") are allowed but must be paired, i.e. open and closing.
^(?=__even_quotes_pattern__$)
Basically, we say that from the start (^), when we iterate til the end ($) we match the said pattern, aka even number of ".
No white space is allowed between a double quote and the word it adjacently wraps.
We will split this in two parts - doesn't happen on the left, doesn't happen on the right:
^(?!__even_quotes_pattern__" \w)
^(?!__even_quotes_pattern__\w ")
Paired double quotes must wrap one or more words.
^(?!__even_quotes_pattern__" *")
(there are no paired quotes that wrap only spaces)
The rest of them are easier:
There must be one or more words.
^(?=.*\b)
(at some point there is a word boundary (\b))
Single quotes (') are not allowed.
(or from the interpretation in the comments, not allowed except for the ones that wrap the string)
^'[^']*'$
An asterisk (*) is not allowed unless it immediately precedes a closing double quote and follows a word, without whitespace.
We will split this into three parts:
(1) Must precede a ":
(?!.*\*[^"])
(2) Must follow a non-" or space
(?!.*[ "]\*)
(3) It doesn't precede non-closing ":
(?!__even_quotes_pattern__[^"]*\*")
clean and simple function:
function myParser(string) {
var string = string.trim(),
wordsArray = string.split(' '),
regExp = /((?=")^["][a-zA-Z]+[*]{0,1}["]$|^[a-zA-Z]+$)/,
len = wordsArray.length,
i = 0;
// '"foo bar"' situation
if (string.match(/^["][a-zA-Z]+[\s]?[a-zA-Z]+[*]{0,1}["]$/)) {
return true;
}
for (i; i < len; i++) {
var result = wordsArray[i].match(regExp);
if (result === null) {
return false;
}
}
return true;
}
https://jsfiddle.net/cy9ozmdm/ to check results.
If you need explanations - write in comment, I will write logic detailed.
(Idea for you: check 2 variants (clear regExp and function) - on 10.000 test situation - what works faster (and doesn't fail :))?)
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
$('#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)
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