Buchannon
Buchannon

Reputation: 1691

JavaScript Regex - Match a string with that contains some characters and doesn't contain others

Requirements:

The regex should match a string that does not contain the "@" symbol, but contains at least two alpha characters, and is between 2 and 50 characters long total.

Pass examples:

"Hi there!%%#"
"         fd"
"  9 z 80212132 z"

Fail examples:

"anything with @"
"a"
"  9 z 80212132 "
"This string does not contain at symbol and has two characters but is too long!"

I believe I am close, however this will fail with any characters other than [a-zA-Z] and I'm not sure why:

^((?![@])(?=[a-zA-Z]).){2,50}$

Upvotes: 1

Views: 193

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627448

Your regex does not check for at least two alphas.

You can use the following regex:

^(?=(?:[^A-Za-z]*[A-Za-z]){2})[^@]{2,50}$

See the regex demo

Explanation:

  • ^ - start of string
  • (?=(?:[^A-Za-z]*[A-Za-z]){2}) - there must be at least two occurrences of zero or more non-alpha characters followed with one alpha
  • [^@]{2,50} - 2 to 50 characters other than @
  • $ - end of string.

var re = /^(?=(?:[^A-Za-z]*[A-Za-z]){2})[^@]{2,50}$/; 
var strs = ['Hi there!%%#', '         fd' , '  9 z 80212132 z', 'anything with @ a', '  9 z 80212132 ', 'This string does not contain at symbol and has two characters but is too long!'];
 // demo
for (var s of strs) {
  document.body.innerHTML += "<i>" + s.replace(/ /g, '&nbsp;') + "</i> test result: <b>" +  re.test(s) + "</b><br/>";
}

Upvotes: 2

Enissay
Enissay

Reputation: 4953

It makes sure:

  • no char is @
  • 2 alpha chars at least
  • total between 2 & 50

^(?!.*@)(?=(?:.*[a-zA-Z]){2}).{2,50}$

DEMO

Upvotes: 0

Related Questions