I want to get the input from the user as 888-999-6666..i.e. 3 numbers then a '-' then 3 numbers then again '-' and finally 4 numbers.
I am using the following regular expression in my JavaScript.
var num1=/^[0-9]{3}+-[0-9]{3}+-[0-9]{3}$/;
if(!(form.num.value.match(num1)))
{
alert("Number cannot be left empty");
return false;
}
But its not working.
If I use var num1=/^[0-9]+-[0-9]+-[0-9]$/; then it wants at least two '-' but no restriction on the numbers.
How can i get the RE as my requirement? And why is the above code not working?
Remove the + symbol which are present just after to the repetition quantifier {} . And replace [0-9]{3} at the last with [0-9]{4}, so that it would allow exactly 4 digits after the last - symbol.
var num1=/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/;
DEMO
You could also write [0-9] as \d.
Your regex should be:
var num1=/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/;
There is an extra + after number range in your regex.
Issue in your regex.check below example.
var num='888-999-6668';
var num1=/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/;
if(!(num.match(num1)))
{
alert("Number cannot be left empty");
}else{
alert("Match");
}
In your example there is extra + symbole after {3}, which generate issue here. so i removed it and it worked.
var num1=/^\d{3}-\d{3}-\d{4}$/;
I think this will work for you.
The rest of your code will be the same.
Related
I currently use the following regex from http://regexlib.com to validate the incoming date using the pattern YYYY-MM-DD. But the leading zeroes are mandatory and I want it to be optional.
((((1[26]|2[048])00)|[12]\d([2468][048]|[13579][26]|0[48]))-((((0[13578]|1[02])-(0[1-9]|[12]\d|3[01]))|((0[469]|11)-(0[1-9]|[12]\d|30)))|(02-(0[1-9]|[12]\d))))|((([12]\d([02468][1235679]|[13579][01345789]))|((1[1345789]|2[1235679])00))-((((0[13578]|1[02])-(0[1-9]|[12]\d|3[01]))|((0[469]|11)-(0[1-9]|[12]\d|30)))|(02-(0[1-9]|1\d|2[0-8]))))
Debuggex Demo
Test case
2000-01-01
2000-1-1
2000-01-1
2000-1-01
are all valid. But only the first test case is accepted, as of now.
Can you please help?
You can achieve this much more simply using a function rather than a regular expression. The following is much simpler to understand and therefore maintain (though it shouldn't ever need any), and is a lot less code that the regular expression in the OP.
function isValidISODate(s) {
var b = s.split(/\D/);
var d = new Date(b[0],--b[1],b[2]);
return d && d.getMonth() == b[1];
}
// Some tests
['2016-1-1','2016-01-01','2016-2-29','2016-02-30'].forEach(
s=>console.log(s + ': ' + isValidISODate(s))
);
You can make a number optional by adding them the number of permitted ocurrences {0,1}. That is {1,2} to accept either 1 character or 2.
A simple version:
[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}
Edit: Your version is easy to "fix". Simply add {0,1} after the compulsory 0:
// Before.
((((0[13578]
// After.
((((0{0,1}[13578]
Edit2: As #Toto has said {0,1} is the same as ?
((((0?[13578]
Using this regex - '\d+-[0-2]* [0-9]-[0-3]* [0-9]' may help .
I am using following regex to 'insert' commas into numbers in javascript.
(\d)(?=(\d{3})+(?!\d))
It works very well with integers however when working with decimal numbers it fails cases like 10000.001223456 (result is 1,234,568.0,000,454,554)
What happens regex looks ahead after '.' finds match and replaces it with ,
Example here
I tried remedy it by adding negative lookbehind without luck,
((\d)(?=(\d{3})+(?!\d))(?<!\.))
since '.' can be at any position in sequence and I cannot use * nor +.
How do I make regex that would not match after some specific symbol (in this specific case after '.')?
You can achieve this only in 3 steps:
Split the number into integer and decimal parts
Modify the integer part
Join.
There is no variable-width look-behind in JS that would be very handy here.
var s = ".12345680000454554";
//Beforehand, perhaps, it is a good idea to check if the number has a decimal part
if (s.indexOf(".") > -1) {
var splts = s.split(".");
//alert(splts);
splts[0] = splts[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
//alert(splts[0]);
s = splts.join(".");
alert(s);
}
else
{
alert(s.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'));
}
$('#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 regex problem with validation for a region code.
My region code could be only one digit but it also could be a digits separated by '-'
for Example my region code could be one of the following:
6
6-66
77-7
As you can see I must have at least one digit or digits separated by '-' and if they are separated there should be a digits after the '-' sign (does not matter how many). So 6- must not be validated as legal region code. I try 2 hours to solve this, but I couldn't, so please help me! Thank you!
/\d+(-\d+)?$/
This will match 6, 6-66,77-7, but not6-`
If what you are looking for is the whole string:
/^\d+(?:-\d+)?$/
or something like that:
if (parseInt(yourstring.split(/-/)[0])>=eval(yourstring)) alert('true');
else alert('false');
But it is more complicated :) and less efficient! And if the condition is false you code will crash!
var data = ['6', '6-66', '77-7', '6-'];
var len = data.length;
for(var i=0; i<len; ++i) {
var current = data[i];
var result = data[i].match(/^(\d+|\d+[-]\d+)$/);
if(result != null) {
console.log(current);
}
}
--output:--
6
6-66
77-7
For a quick answer you can try following:
/^([0-9])|([0-9]\-[0-9][0-9])|([0-9][0-9]\-[0-9])$/
or in case your engine support perl-styled character classes:
/^(\d)|(\d\-\d\d)|(\d\d\-\d)$/
here what it does:
between / and / resides as string defining a regular expression
\d stands for one digit it coudl also be writen as [0-9]
() defines a sub-expression, so (\d) matches your first one-digit, (\d-\d\d) second three digits style, and last (\d\d-\d) third variant of three-digit region code
| goes as "OR" like (A)|(B)|(C), so by combining previous three we will get:
/(\d)|(\d-\d\d)|(\d\d-\d)/
Finally ^ means start of string, and $ - end of string.
also there is so called BRE mode (in which you have to add "\" symbol before each parentheses), but I think it is not the case. However if you would have some free time, please consider any quick tutorial like this one.
I'm trying to write a regex to verify that an input is a pure, positive whole number (up to 10 digits, but I'm applying that logic elsewhere).
Right now, this is the regex that I'm working with (which I got from here):
^(([1-9]*)|(([1-9]*).([0-9]*)))$
In this function:
if (/^(([1-9]*)|(([1-9]*).([0-9]*)))$/.test($('#targetMe').val())) {
alert('we cool')
} else {
alert('we not')
}
However, I can't seem to get it to work, and I'm not sure if it's the regex or the function. I need to disallow %, . and ' as well. I only want numeric characters. Can anyone point me in the right direction?
You can do this way:
/^[0-9]{1,10}$/
Code:
var tempVal = $('#targetMe').val();
if (/^[0-9]{1,10}$/.test(+tempVal)) // OR if (/^[0-9]{1,10}$/.test(+tempVal) && tempVal.length<=10)
alert('we cool');
else
alert('we not');
Refer LIVE DEMO
var value = $('#targetMe').val(),
re = /^[1-9][0-9]{0,8}$/;
if (re.test(value)) {
// ok
}
Would you need a regular expression?
var value = +$('#targetMe').val();
if (value && value<9999999999) { /*etc.*/ }
var reg = /^[0-9]{1,10}$/;
var checking = reg.test($('#number').val());
if(checking){
return number;
}else{
return false;
}
That's the problem with blindly copying code. The regex you copied is for numbers including floating point numbers with an arbitrary number of digits - and it is buggy, because it wouldn't allow the digit 0 before the decimal point.
You want the following regex:
^[1-9][0-9]{0,9}$
Use this regular expression to match ten digits only:
#"^\d{10}$"
To find a sequence of ten consecutive digits anywhere in a string, use:
#"\d{10}"
Note that this will also find the first 10 digits of an 11 digit number. To search anywhere in the string for exactly 10 consecutive digits.
#"(?<!\d)\d{10}(?!\d)"
check this site here you can learn JS Regular Expiration. How to create this?
https://www.regextester.com/99401