I want to get the input from the user as 888-999-6666..ie 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}$/;
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.