I donβt think it would be easy to check if you have at least 5 unique characters with regular expression, so I use a different approach.
I check preg_match() that your string contains only characters from this [a-zA-Z0-9] and at least 7 characters long, which I check with quantifier : {7,} .
Then, to make sure that you have> = 5 unique characters, I split your string into an array with str_split() , get all the unique characters of array_unique() and check the count() box if there are> = 5 unique characters, e.g.
if(preg_match("/^[a-zA-Z0-9]{7,}$/", $input) && count(array_unique(str_split($input))) >= 5) { //good } else { /bad }
As, from the question, it is unclear whether you want to perform validation in php or javascript by adding similar code using Javascript.
var regex = /^[a-zA-Z0-9]{7,}$/;
.valid { border: solid 1px green; } .invalid { border: solid 1px red; }
<input id="text" type="text" />
For completeness only, there will be a solution with a regular expression only:
~^ (?=.{7,}) ([az\d])[az\d]* (?!\1)([az\d])[az\d]* (?!\1|\2)([az\d])[az\d]* (?!\1|\2|\3)([az\d])[az\d]* (?!\1|\2|\3|\4)([az\d])[az\d]* $~i
Simply put:
(?=.{7,}) ensures that there must be at least 7 characters from the very beginning to the end of the line- Then there are 5 capture groups with a negative look that guarantee that their match cannot be in any other of the 4 capture groups. Thus, this ensures that the string contains at least 5 unique characters.
[az\d]* around capture and negative look groups just say there can be all kinds of things around these 5 unique characters.
(Regular expression can still be optimized)
source share