I want to check an input string to validate a proper text. The validation will be done with javascript and right now I’m using this code:
keychar = String.fromCharCode(keynum);
var text = txtBox.value + keychar;
textcheck = /(?!.*(.)\1{1})^[fenFN,]*$/;
return textcheck.test(text);
The strings that are allowed are for example:
f
e
f,e
n,f,e,F,N
Examples of not allowed:
ff
fe
f,f
f,ee
f,e,n,f
n,,(although this could be ok)
Is this possible to solve with regex in Javascript?
I don’t think you can do it with regexps alone, as they are not very good at looking around in the text for duplicates. I’m sure it can be done, but it won’t be pretty at all.
What you might want to do is parse the string character by character and store the current character in an array, and while you’re parsing the string, check to see if that character has already been used, as follows:
You might also want to make sure that the browser you are running this on supports Array.indexOf by including this script somewhere: Mozilla indexOf