php - How to check that a string contains at least 5 unique characters and is minimum 7 characters long? -


i need validation tests string contains 5 unique characters , @ least 7 characters long.

i have tried following regex:

^[a-za-z][0-9]{7}$   

i'm stuck , have no idea how validation string contains @ least 5 unique characters.

i don't think easy check if have @ least 5 unique characters in there regex, use approach.

i check preg_match(), string contains characters character class [a-za-z0-9] , @ least 7 characters long, check quantifier: {7,}.

then make sure have >= 5 unique characters, split string array str_split(), unique characters array_unique() , check count() if there >= 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, question not clear if want perform validation in or , adding similar code using javascript.

var regex = /^[a-za-z0-9]{7,}$/;    // adding method on prototype, can invoked on array  array.prototype.unique = function() {    var arr = this; // cache array      // return array removing duplicates    return this.filter(function(e, i) {      return arr.indexof(e) === i;    });  };    // binding keyup event on textbox(demo purpose)  document.getelementbyid('text').addeventlistener('keyup', function(e) {    var str = this.value; // value      this.classlist.remove('invalid'); // remove classes      // check if regex satisfies, , there unique elements required    if (regex.test(str) && str.split('').unique().length >= 5) {      console.log('valid');      this.classlist.add('valid'); // demo purpose    } else {      console.log('invalid');      this.classlist.add('invalid'); // demo purpose    }  }, false);
.valid {    border: solid 1px green;  }  .invalid {    border: solid 1px red;  }
<input id="text" type="text" />


just completeness, here solution regex:

~^   (?=.{7,})     ([a-z\d])[a-z\d]*     (?!\1)([a-z\d])[a-z\d]*     (?!\1|\2)([a-z\d])[a-z\d]*     (?!\1|\2|\3)([a-z\d])[a-z\d]*     (?!\1|\2|\3|\4)([a-z\d])[a-z\d]* $~i 

simply explained:

  • (?=.{7,}) makes sure start till end of string there @ least 7 characters
  • then there 5 capturing groups negative lookahead's, make sure match can't in other of 4 capturing groups. makes sure there @ least 5 unique characters in string
  • the [a-z\d]* around capturing groups , negative lookahead's there say, there can kinds of stuff around these 5 unique characters

(the regex maybe still optimized)


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -