Reputation: 35
I am preparing a regular expression validation for text box where person can enter only 0-9,*,# each with comma seprated and non repeative. I prepared this
if( ( incoming.GET_DTMF_RESPONSE.value.match(/[0-9*#]\d*$/)==null ) )
alert("DTMF WRONG"
where incoming is functions back and GET_DTMF_RESPONSE is textbox name
I am not good in Regex..it is accepting 0-9 and * and # thats good but it is accepting a-z also i want it to make non repeative numbers and no alphabet and no special character excepting #,*
Let me know how to do this
Upvotes: 0
Views: 3584
Reputation: 32797
How about this regex
^(?!.*,$|.*\d{2,})(?:([\d*#]),?(?!.*\1))+$
For each value separated by comma am capturing it into group1 and then am checking if it occurs ahead using \1
(backreference)
^
marks the beginning of string
(?!.*,$|.*\d{2,})
is a lookahead which would match further only if the string doesn't end with ,
or has two or more digits
In (?:([\d*#]),?(?!.*\1))+
a single [\d*#]
is captured in group 1
and then we check whether there is any occurrence of it ahead in the string using (?!.*\1)
. \1
refers to the value in group 1.This process is repeated for each such value using +
$
marks the end of string
For example
for Input
1,2,4,6,2
(?!.*,$|.*\d{2,})
checks if the string doesn't end with ,
or has two or more digits
The above lookahead only checks for the pattern but doesn't match anything.So we are still at the beginning of string
([\d*#])
captures 1
in group 1
(?!.*\1)
checks(not match) for 1
anywhere ahead.Since we don't find one,we move forward
Due to +
we would again do the same thing
([\d*#])
would now capture 2
in group 1
(?!.*\1)
checks(not match) for 2
anywhere ahead.Since we find it,we have failed matching the text
works here
But you better use non regex solution as it would be more simple and maintainable..
var str="1,2,4,6,6";
str=str.replace(/,/g,"");//replace all , with empty string
var valid=true;
for(var i=0;i<str.length-1;i++)
{
var temp=str.substr(i+1);
if(temp.indexOf(str[i])!=-1)valid=false;
}
//valid is true or false depending on input
Upvotes: 5
Reputation: 89557
You can use this:
^(?:([0-9#*])(?!(?:,.)*,\1)(?:,|$))+$
Upvotes: 0