Udaan Udaan - 1 year ago 67
Javascript Question

Regex to use in JavaScript string with not more than n number of digits

I'm trying to validate a username in jquery using a regex, with following rules

  • String must start with a letter

  • String can have 0(m) to 4(n) digits anywhere or no more than 4(n)

  • Size of the string must be between 6(p) and 20(q)

Following should fail

  • 1djgWWq
    (starts with a digit)

  • wwwhg
    (length less than 6)

  • ky12yu781
    (more than 4 digits)

Following should pass

  • tableten

  • table10

  • tab7le10

I tried following regex which is good, except its not match 4 digits anywhere in the string


Sample regex101

Note: m,n, p,q integer variable


Sebastian Proske> Yes letters numbers and _ -
I want to try validate fields in a form using different regex for each field, so regex per one filed, I want to stick to one regex for cleaner code.
bellow is sample untested code to give you a idea what I'm trying to do.
Sebastian Proske answer is the best one for my work. Thanks everyone.

Sample 1<input id="ds1" type="text" class="validate" data-validate='{"regex":"^[a-z0-9]{4,7}$"}' /><br/>
Sample 2...
Sample 3...
Active Sample <input id="as" type="text" class="validate" data-validate='{"regex":"^(?=^[A-Za-z]+[A-Za-z0-9_-]{5,20}$)(?=^(?:(?!\d{4}).)*$).*$"}' /><br/>
<input id="f1SubmitBtn" type="button" value="Test" onclick="f1Submit();" /><br/>
function f1Submit() {
$('.validate').each(function() {
if (!$(this).data('validate').regex.test(this.value)) {
console.log(this.value + " No!");

Answer Source

From your original regex I assume that _ and - are also allowed characters. You can test your names with the regex /^(?!(?:\D*\d){5})[a-z][\w-]{5,19}$/i.

A little breakdown:

  • ^ is an anchor for the start of the string
  • (?!(?:\D*\d){5}) is a negative lookahead checking for the presence of 5 digits (which will cause the match to fail)
  • [a-z] the first character has to be a letter
  • [\w-]{5,19} length between 6 and 20, word characters ([a-zA-Z0-9_]) and minus are allowed
  • $ is an anchor for the end of the string
  • i is the case-insensitivity modifier

See Regex101

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download