I want to disable letters in my textbox, that's why I used this expression:
/^[0-9]*$/
The problem is that I want to allow negative numbers too,
and this expression does'nt enable me to use minus sign.(-)..
What shuold I do?
Try with following regexp:
/^-?[0-9]*$/
More correctly: /^(?:- *)?[0-9]+$/
Since it is usually allowed to have one or more spaces between the minus sign and the digits. Also, you must have at least one digit to have a valid number.
If you decide you want to match all kinds of numbers, including floating point, this is a good read. If you just want to match simple integers with an optional "minus" sign, then go with hsz's answer, though I might change the * to a +.
Use the isNaN() function of JavaScript.
Here is a code below:
$(document).ready(function () {
numbersPlusMinus();
});
function numbersPlusMinus() {
var inputPrev = "";
$(".toNumberPlusMinus").change(function () {
if (isNaN($(this).val())) {
$(this).val(inputPrev);
} else {
inputPrev = $(this).val();
}
});
}
Related
I'am trying to allow following pattern for a single html input box with javascript regex
-int (aka any minus number so long it not followed by a zero and is in the first position)
0 (a single zero is allowed)
int (is allowed)
I use this function the remove anything that doesn't match it
$('.dointcheck').live('keyup',
function () {
$(this).val($(this).val().replace((/^((?!:([1-9-]?[0-9])).)/g), ''));
if ($(this).val().length == 0) {
$(this).val(0);
}
});
which doesn't work.
Other examples is:
/[^-0-9]/g it removes any non valid chars but doesnt check if the minus is the beginning and is followed by a zero. It allows minus everywhere in the string
(/^((?!:([1-9-]?[0-9])).)/g Don't allow none.
[^1-9-]?[^0-9]* Allow all...
I think I'am missing something.. Any suggestions would be most appreciated..
You may try this regex
^(0).*|^(-?)([1-9]\d*)?.*|^.*
and replace it with $1$2$3 after input
document.querySelector('input').addEventListener('input', ({ target }) => target.value = target.value.replace(/^(0).*|^(-)?([1-9]\d*)?.*|^.*/g, '$1$2$3'));
<input />
It has three tests:
^(0).* // if it starts with 0, discard everything after it
^(-)?([1-9]\d*)?.* // otherwise it can only starts with a -, or any number that is not a 0. Then followed by other digits, then discard everything after it
^.* // if previous rules are not matched, discard everything
In short:
generally only -, 0-9 are allowed.
if you type a 0 first, nothing will be allowed after.
if you type a 1-9 first, only numbers are allowed after.
if you type a - first, only 1-9 is allowed next, then any digit is allowed after.
I changed your regexp and made it a bit more modular and it worked fine.
function toValidNumber(int) {
return (/^\s*[+-]?(\d+|\d*\.\d+|\d+\.\d*)([Ee][+-]?\d+)?\s*$/).test(int) ? int : 0;
}
$('.dointcheck').live('keyup',
function () {
$(this).val(toValidNumber($(this).val()));
});
Orginal RegEXP in Stackoverflow
var category = prompt("where do you go? (1~99)", "");
hello
Using regular expressions I want to determine if the category is 1-99.
How can I solve it?
Thank you if you let me know.
You can use character classes to match digits, like this [0-9]. If you put two of them together you'll match 00 - 99. If you put a ? after one of them, then it's optional, so you'll match 0 - 99. To enforce 1-99, make the non-optional one like this [1-9]. Finally, you need to make sure there's nothing before or after the one or two digits using ^, which matches the beginning of the string, and $ which matches the end.
if (category.match(/^[1-9][0-9]?$/)){
console.log("ok")
} else {
console.log("not ok")
}
In JavaScript you can use test() method with RE for 1-99 as shown below:
var one_to_ninetynine = /^[1-9][0-9]?$/i;
if(one_to_ninetynine.test(category)) {
console.log("The number is between 1-99");
} else {
console.log("The number is NOT between 1-99");
}
I'm using this Wordpress plugin called 'Easy contact form' which offers standard validation methods.
It uses the following regex for phone numbers:
/^(\+{0,1}\d{1,2})*\s*(\(?\d{3}\)?\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/
Just now it allows the following formats (maybe more):
0612345678
+31612345678
But I want it to allow +316-12345678 and 06-12345678 also ... Is this possible? If so, how?
Thanks in advance!
You can use a less complex regex :
^\+?\d{2}(-?\d){8,9}$
This regex allows a + at the beginning of the phone number, then matches two digits, and after that, digits preceded (or not) by a -, for a total of 10 or 11 digits.
Now you can adapt it if the initial + is only for 11-digits phone numbers :
^\+?\d{3}(-?\d){9}|\d{2}(-?\d){8}$
My regex allow you to use - every digit. If that's an issue, it can be changed :
^\+?\d{3}(-?\d{2}){4}|\d{2}(-?\d{2}){4}$
I think this last regex will answer your needs, and it's quite simple !
When you figure out what patterns you actually want to allow and not allow. Then fill them out in this function and if the statement returns true you have your regex.
var regex = /^\+?\d{3}(-?\d{2}){4}|\d{2}(-?\d{2}){4}$/; //this is your regex, based on #Theox third answer
//allowed patterns
['0612345678', '+31612345678', '+316-12345678', '06-12345678'].every(function(test) {
return regex.exec(test) !== null;
}) &&
//disallowed patterns, none right now
[].every(function(test) {
return regex.exec(test) === null;
});
I've made a function to live control numbers and float numbers.
But it doesn't work properly for float numbers, which have to be like this expression:
// I wish a number like x figures . 3 figures (example : 123456.123)
/^([1-9][0-9]*|0)(\.[0-9]{3})?$/
But this expression makes disappear the dot...
The follow works /(^\d+$)|(^\d+\.\d+$)|[,.]/, but multiple dots can be added:
$('.float_input').live("keypress",function(){inputControl($(this),'double');});
function inputControl(input,format)
{
var value=input.val();
if (format=='int'){expression=/(^\d+$)|(^\d+\.\d+$)/;}
else if (format=='double'){expression=/(^\d+$)|(^\d+\.\d+$)|[,.]/;}
var values=value.split("");
var update="";
for(id in values)
{
if (expression.test(values[id])==true && values[id]!='')
{
// also replace ',' by '.'
update=update+''+values[id].replace(',','.');
}
}
input.val(update);
}
So I have multiple dots or no dot, it makes me nutty because I'm sure to be near the solution.
EDIT > SOLUTION
Ouch, thanks for the help about regex, I've found the solution!
Two tests were necessary:
one for the characters test, tested one by one
another to test the entire input while entering characters
This is the final script, which works like a flower, and I share it just for you:
$('.numeric_input').live("keyup",function(){inputControl($(this),'int');});
$('.float_input').live("keyup",function(){inputControl($(this),'float');});
function inputControl(input,format)
{
var value=input.val();
var values=value.split("");
var update="";
var transition="";
if (format=='int'){
expression=/^([0-9])$/;
finalExpression=/^([1-9][0-9]*)$/;
}
else if (format=='float')
{
var expression=/(^\d+$)|(^\d+\.\d+$)|[,\.]/;
var finalExpression=/^([1-9][0-9]*[,\.]?\d{0,3})$/;
}
for(id in values)
{
if (expression.test(values[id])==true && values[id]!='')
{
transition+=''+values[id].replace(',','.');
if(finalExpression.test(transition)==true)
{
update+=''+values[id].replace(',','.');
}
}
}
input.val(update);
}
This regex
(/(^\d+$)|(^\d+.\d+$)|[,.]/)
should match
1111111 per the (^\d+$)
or 111111.11111 per the (^\d+.\d+$)
or the comma followed by any character, and it could be anywhere in the expression.
I'm suspecting your regex should be
Note that I've escaped the final period. That would match a comma or a period
/(^\d+[,\.]{0,1}\d{3})/
may be exactly what you want based on clarifications in the comments
[-+]?[0-9]*\.?[0-9]+
would also work
NOTE: You can simplify your regex life tremendously by using Roy Osherove's Regulazy or the tool Regex Buddy.
You want arbitrary amount of digits behind the decimal point (comma or period)?
What's wrong with:
/^([1-9][0-9]*|0)([\.,][0-9]+)?$/
I switched out the {3} for + and \. for [\.,]
This works:
var.replace(/[^0-9]+/g, '');
That simple snippet will replace anything that is not a number with nothing.
But decimals are real too. So, I'm trying to figure out how to include a period.
I'm sure it's really simple, but my tests aren't working.
Simply: var.replace(/[^\d.-]+/g, '');
Replacing something that is not a number is a little trickier than replacing something that is a number.
Those suggesting to simply add the dot, are ignoring the fact that . is also used as a period, so:
This is a test. 0.9, 1, 2, 3 will become .0.9123.
The specific regex in your problem will depend a lot on the purpose. If you only have a single number in your string, you could do this:
var.replace(/.*?(([0-9]*\.)?[0-9]+).*/g, "$1")
This finds the first number, and replaces the entire string with the matched number.
Try this:
var.replace(/[^0-9\\.]+/g, '');
there's a lot of correct answers already, just pointing out that you might need to account for negative signs too.. "\-" add that to any existing answer to allow for negative numbers.
Try this:
var.replace(/[0-9]*\.?[0-9]+/g, '');
That only matches valid decimals (eg "1", "1.0", ".5", but not "1.0.22")
If you don't want to catch IP address along with decimals:
var.replace(/[^0-9]+\\.?[0-9]*/g, '');
Which will only catch numerals with one or zero periods
How about doing this:
var numbers = str.gsub(/[0-9]*\.?[0-9]+/, "#{0} ");
Sweet and short inline replacing of non-numerical characters in the ASP.Net Textbox:
<asp:TextBox ID="txtJobNo" runat="server" class="TextBoxStyle" onkeyup="this.value=this.value.replace(/[^0-9]/g,'')" />
Alter the regex part as you'ld like. Lots and lots of people complain about the cursor going straight to the end when using the arrow keys, but people tend to deal with this without noticing it for instance, arrow... arrow... arrow... okay then... backspace back space, enter the new chars.
Here are a couple of jQuery input class types I use:
$("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 allows only numeric - like other solutions here.
nmbr allows only positive/negative decimal. Negative must be the first character (you can add "+" to the filter if you need it), strips -3.6.23.333 to -3.623333
I'm putting nmbr up because I got tired of trying to find the way to keep only 1 decimal and negative in 1st position
This one just worked for -ve to +ve numbers
<input type="text" oninput="this.value = this.value.replace(/[^0-9\-]+/g, '').replace(/(\..*)\./g, '$1');">
I use this expression to exclude all non-numeric characters + keep negative numbers with minus sign.
variable.replace(/[^0-9.,\-]/g,'')